void CUartChannel::ManualConfigPort(void) { COMMCONFIG conf; char str[20]; if(this->IsOpened() == FALSE) return; sprintf(str, "COM%d", this->m_Port); CommConfigDialog(str, NULL, &conf); }
////////////////////////////////////////////////////////////////////// // ShowConfigDialog // return: 0 success // -1 error // int CAsyncPort::ShowConfigDialog(HWND hWnd) { COMMCONFIG commConfig; //memset(& commConfig, 0, sizeof (COMMCONFIG)); //commConfig.dwSize = sizeof(COMMCONFIG); memcpy(& commConfig, & m_commConfig, sizeof (COMMCONFIG)); if (! CommConfigDialog(m_szCommDevName, hWnd, & commConfig)) { return -1; } return SetupConnection(commConfig.dcb); }
/** * Initialises a serial port handle for reading and writing * * @param LPCTSTR port The name of the serial port to open. * @param HANDLE* fd The pointer to the handle which will be initialised to the open * serial port connection. * @returns int 0 on success, >0 otherwise */ int OpenPort(const LPCTSTR port, HANDLE* fd, HWND hwnd) { COMMPROP cprops; DCB dcb; COMMCONFIG config; /* Create the file descriptor handle */ if ((*fd = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL)) == INVALID_HANDLE_VALUE) { return 1; } if (!GetCommProperties(*fd, &cprops)) { return 2; } /* Setup the port for sending and receiving data */ if (!SetupComm(*fd, cprops.dwMaxRxQueue, cprops.dwMaxTxQueue)) { return 3; } /* Get the current DCB settings */ if (!GetCommState(*fd, &dcb)) { return 4; } config.dwSize = sizeof(COMMCONFIG); config.wVersion = 0x1; config.dcb = dcb; config.dwProviderSubType = cprops.dwProvSubType; config.dwProviderOffset = 0; config.dwProviderSize = 0; /* Show the port configuration dialog */ if (!CommConfigDialog(port, hwnd, &config)) { return 5; } /* Set the DCB to the config settings */ if (!SetCommState(*fd, &config.dcb)) { return 6; } /* Specify events to receive */ if (!SetCommMask(*fd, EV_RXCHAR | EV_TXEMPTY)) { return 7; } return 0; }
/*----------------------------------------------------------------------------- - FUNCTION: ConfPort - - DATE: September 20th, 2013 - - REVISIONS: VincentLau - Edited parameters to take in an opened port name - 2013/11/15 - - DESIGNER: Vincent Lau - - PROGRAMMER: Vincent Lau - - INTERFACE: bool ConfigurePort (HWND* lphwnd, LPTSTR* lpszOpenedPort) - - PARAMETERS: HWND* lphwnd - Pointer to the main window's handle - LPTSTR lpszOpenedPort - Name of the serial port that is connected - - RETURNS: TRUE - if the configuration was successful - FALSE - if a configuration error occured or the dialog was canceled - - NOTES: Brings up the Win32 COMMCONFIG dialog for the user to adjust any - settings for communication. Will also set the state of the comm - device and get+set the default timeouts for the specified port. - -----------------------------------------------------------------------------*/ BOOL ConfPort (HWND* lphwnd, LPTSTR lpszOpenedPort) { COMMCONFIG cc; COMMTIMEOUTS comTimeout; cc.dwSize = sizeof (COMMCONFIG); cc.wVersion = 0x100; // Get defaults GetCommConfig (hComm, &cc, &cc.dwSize); // Allow user to change settings from this config dialog if (!CommConfigDialog (lpszOpenedPort, *lphwnd, &cc)) return FALSE; PurgeComm(hComm, PURGE_RXCLEAR | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_TXABORT); return TRUE; }
LRESULT CALLBACK WndProc (HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { HDC hdc; LPDCB lpDCB = &cc.dcb; static int cxClient,cyClient; PAINTSTRUCT ps; static int iVertPos = 0; SCROLLINFO si; char buffer[128] = {0}; DWORD bytesRead; DWORD bytesWritten; //OVERLAPPED ov = {0,0,0}; std::fstream ifs; OPENFILENAME ofn; static TCHAR szFilter[] = TEXT ("All Files (*.*)\0*.*\0\0") ; static TCHAR szFileName[MAX_PATH], szTitleName[MAX_PATH] ; char packet[1024]; char packet2[2]; if (cxClient && cyClient) { /*text_area.left = 0; text_area.top = 0; text_area.right = cxClient; text_area.bottom = cyClient; areaset = true;*/ topright.left = cxClient - cxClient/3 + 1; topright.top = 1; topright.right = cxClient; topright.bottom = cyClient - cyClient/3 - 1; topleft.left = 1; topleft.top = 1; topleft.right = cxClient - cxClient/3 - 1; topleft.bottom = cyClient - cyClient/3 - 1; } switch (Message) { case WM_CREATE: ov.Offset = 0; ov.OffsetHigh = 0; ov.Pointer = 0; ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); semm = CreateSemaphore(NULL, 0, 1, NULL); global.hSem = &semm; InitializeCriticalSection(§ion); break; case WM_COMMAND: switch (LOWORD (wParam)) { case IDM_COM1: cc.dwSize = sizeof(COMMCONFIG); cc.wVersion = 0x100; if (!CommConfigDialog (lpszCommName1, hwnd, &cc)) break; else { comset = true; curCom = 1; } break; case IDM_COM2: cc.dwSize = sizeof(COMMCONFIG); cc.wVersion = 0x100; if (!CommConfigDialog (lpszCommName2, hwnd, &cc)) break; else { comset = true; curCom = 2; } break; case IDM_COM3: cc.dwSize = sizeof(COMMCONFIG); cc.wVersion = 0x100; if (!CommConfigDialog (lpszCommName3, hwnd, &cc)) break; else { comset = true; curCom = 3; } break; case IDM_COM4: cc.dwSize = sizeof(COMMCONFIG); cc.wVersion = 0x100; if (!CommConfigDialog (lpszCommName4, hwnd, &cc)) { break; }else { comset = true; curCom = 4; } break; case IDM_Connect: //WaitForSingleObject(ov.hEvent, INFINITE); //MessageBox(hwnd, TEXT(""), TEXT(""), MB_OK); if (comset) { if (curCom == 1) { if ((hComm = CreateFile (lpszCommName1, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL)) == INVALID_HANDLE_VALUE) { MessageBox (NULL, TEXT("Error opening COM port:"), TEXT(""), MB_OK); return FALSE; } } else if (curCom == 2) { if ((hComm = CreateFile (lpszCommName2, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, NULL, NULL)) == INVALID_HANDLE_VALUE) { MessageBox (NULL, TEXT("Error opening COM port:"), TEXT(""), MB_OK); return FALSE; } } else if (curCom == 3) { if ((hComm = CreateFile (lpszCommName3, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, NULL, NULL)) == INVALID_HANDLE_VALUE) { MessageBox (NULL, TEXT("Error opening COM port:"), TEXT(""), MB_OK); return FALSE; } } else if (curCom == 4) { if ((hComm = CreateFile (lpszCommName4, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL)) == INVALID_HANDLE_VALUE) { MessageBox (NULL, TEXT("Error opening COM port:"), TEXT(""), MB_OK); return FALSE; } } lpDCB = &cc.dcb; if (!SetCommState(hComm, lpDCB)) { MessageBox (NULL, TEXT("Error setting COM state"), TEXT(""), MB_OK); return false; } COMMTIMEOUTS timeouts; timeouts.ReadIntervalTimeout = MAXDWORD; timeouts.ReadTotalTimeoutMultiplier = 0; timeouts.ReadTotalTimeoutConstant = 0; timeouts.WriteTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutConstant = 0; if (!SetCommTimeouts(hComm, &timeouts)) { MessageBox (NULL, TEXT("Error setting COM timeouts"), TEXT(""), MB_OK); return false; } if (hComm) { global.hComm = &hComm; global.ov = ov; //opThrd = CreateThread(NULL, 0, OutputThread, (LPVOID)hwnd, 0, &opThrdID ); recvThread = CreateThread(NULL, 0, receiverThread, &global, NULL, &opThrdID); MessageBox(NULL, TEXT("connected"), TEXT(""), MB_OK); } else { MessageBox(NULL, TEXT("Please select a COM port."), TEXT(""), MB_OK); } } else { MessageBox(NULL, TEXT("Please select a COM port."), TEXT(""), MB_OK); } break; case IDM_Disconnect: //kills the reading thread and closes the com port if they are active if (KillReader == false && hComm) { KillReader = true; CloseHandle(hComm); MessageBox(NULL, TEXT("disconnected"), TEXT(""), MB_OK); } break; case IDM_OpenFile: ofn.lStructSize = sizeof (OPENFILENAME) ; ofn.hwndOwner = hwnd ; ofn.hInstance = NULL ; ofn.lpstrFilter = szFilter ; ofn.lpstrCustomFilter = NULL ; ofn.nMaxCustFilter = 0 ; ofn.nFilterIndex = 0 ; ofn.lpstrFile = NULL ; // Set in Open and Close functions ofn.nMaxFile = MAX_PATH ; ofn.lpstrFileTitle = NULL ; // Set in Open and Close functions ofn.nMaxFileTitle = MAX_PATH ; ofn.lpstrInitialDir = NULL ; ofn.lpstrTitle = NULL ; ofn.Flags = 0 ; // Set in Open and Close functions ofn.nFileOffset = 0 ; ofn.nFileExtension = 0 ; ofn.lpstrDefExt = TEXT ("txt") ; ofn.lCustData = 0L ; ofn.lpfnHook = NULL ; ofn.lpTemplateName = NULL ; ofn.hwndOwner = hwnd ; ofn.lpstrFile = szFileName ; ofn.lpstrFileTitle = szTitleName ; ofn.Flags = OFN_HIDEREADONLY | OFN_CREATEPROMPT ; if (GetOpenFileName(&ofn)) { std::wstring wfilename(szFileName); std::string filename; for(int i = 0; i < wfilename.size(); i++) { filename += wfilename[i]; } ifs = OpenFile(filename); readFile(ifs); DWORD threadID; DWORD exitStatus; if (sendThread == 0 || (GetExitCodeThread(sendThread, &exitStatus) && exitStatus != STILL_ACTIVE)) { sendThread = CreateThread(NULL, 0, sendBufferThread, &global, NULL, &threadID); } } } break; case WM_CHAR: // Process keystroke break; case WM_LBUTTONDOWN: break; case WM_SIZE: cxClient = LOWORD(lParam); cyClient = HIWORD(lParam); si.cbSize = sizeof(si); si.fMask = SIF_ALL; si.nMin = 0; si.nMax = cyClient; si.nPos = 0; si.nPage = 50; SetScrollInfo(hwnd, SB_VERT, &si, TRUE); break; case WM_VSCROLL: si.cbSize = sizeof(si); si.fMask = SIF_ALL; GetScrollInfo(hwnd, SB_VERT, &si); iVertPos = si.nPos; switch(LOWORD(wParam)){ case SB_LINEUP: si.nPos -= 10; break; case SB_LINEDOWN: si.nPos += 10; break; case SB_PAGEUP: si.nPos -= si.nPage; break; case SB_PAGEDOWN: si.nPos += si.nPage; break; case SB_THUMBTRACK: si.nPos = si.nTrackPos; break; default: break; } si.fMask = SIF_POS; SetScrollInfo(hwnd, SB_VERT, &si, TRUE); GetScrollInfo(hwnd, SB_VERT, &si); //if there was change in the vertical scroll bar, make adjustments to redraw if (si.nPos != iVertPos){ //InvalidateRect(hwnd, &text_area, TRUE); } break; case WM_PAINT: hdc = BeginPaint(hwnd, &ps); MoveToEx(hdc, cxClient - cxClient/3, 0, NULL); LineTo(hdc, cxClient - cxClient/3, cyClient); MoveToEx(hdc, 0, cyClient - cyClient/3, NULL); LineTo(hdc, cxClient, cyClient - cyClient/3); DisplayStatistics(topright, stats, hdc); //DisplayReceivedFileData(topleft, file, hdc); ReleaseDC(hwnd, hdc); break; case WM_DESTROY: // Terminate program if (hComm) { CloseHandle(hComm); } PostQuitMessage (0); break; default: return DefWindowProc (hwnd, Message, wParam, lParam); } return 0; }
/* FUNCTION: WndProc DATE: 12/2/2015 REVISIONS: v3 - changed all IO operations to overlapped DESIGNER: Dylan & Allen & Thomas PROGRAMMER: Dylan & Allen INTERFACE: LRESULT CALLBACK WndProc (HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) HWND hwnd : handle to the the main window UINT Message : message sent from the message loop to the window WPARAM wParam : parameters to the message LPARAM lParam : parameters to the message RETURNS: The default window procedure or 0 NOTES: Handles all button presses from the main window as well as events from the serial port reading thread */ LRESULT CALLBACK WndProc (HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_CREATE: break; case WM_COMMAND: switch (LOWORD(wParam)) { case ASN_ENQ: if (state != IDLE && state != WAIT) { OutputDebugString("ENQ but not idling\n"); break; } startWriting(); // send ENQ to the serial port and assume it never fails WriteFile(hComm, enq, 1, NULL, &OVERLAPPED()); state = WENQACK; OutputDebugString("ENQ sent\n"); finishWriting(); break; case ASN_SET: startWriting(); if (!CommConfigDialog(TEXT("com1"), hMain, &cc)) { return FALSE; } else { SetCommConfig(hComm, &cc, cc.dwSize); PurgeComm(hComm, PURGE_RXCLEAR); } finishWriting(); break; case ASN_CON: OpenFileDialog(); break; case ASN_CLR: ClearTextBoxes(); break; case ASN_QUIT: PostQuitMessage(0); break; case ASN_HLP: break; case ASN_OPN: OpenFileDialog(); break; case ACK_REC: if (state != WACK && state != WENQACK) { OutputDebugString("ACK received but not waiting for ACK before sending a packet\n"); break; } if (state == WENQACK) { OutputDebugString("ACK received\n"); acksReceived++; SetStatistics(); if (packetBuffer[currentPacket][0] != 0) { OVERLAPPED overlapped = { 0 }; overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); startWriting(); if (!WriteFile(hComm, packetBuffer[currentPacket++], PACKETLENGTH, NULL, &overlapped)) { WaitForSingleObject(overlapped.hEvent, TIMEOUT); } OutputDebugString("Sent a packet\n"); packetsSent++; SetStatistics(); // ENQ the line to send the next packet // THIS SHOULD BE REPLACED BY THE APPROPRIATE PRIORTIY PROTOCOL /* if (packetBuffer[currentPacket][0] != 0) { WriteFile(hComm, enq, 1, NULL, NULL); } */ finishWriting(); } OutputDebugString("Going to WACK state\n"); state = WACK; break; } if (state == WACK) { OutputDebugString("Packet confirmed received\n"); OutputDebugString("Going to WAIT state\n"); state = WAIT; packsAcked++; acksReceived++; SetStatistics(); } break; } break; // end WM_COMMAND case WM_CHAR: break; case WM_SIZE: break; case WM_DESTROY: // Terminate program PostQuitMessage(0); break; default: return DefWindowProc(hwnd, Message, wParam, lParam); } return 0; }
/*------------------------------------------------------------------------------ -- FUNCTION: Connect -- -- DATE: Oct 16, 2010 -- -- REVISIONS: Nov 6, 2010 - Added initialization of rfid scanner and printing -- headers for token display. -- -- DESIGNER: Dean Morin -- -- PROGRAMMER: Dean Morin -- -- INTERFACE: Connect(HWND hWnd) -- hWnd - the handle to the window -- -- RETURNS: True if the serial connection was succefully made. -- -- NOTES: -- Opens a serial port connection, displaying appropriate dialogue -- messages for failed connections. If successful, it sets comm -- settings and creates a read thread. It then enables/disables -- the appropriate menu choices. ------------------------------------------------------------------------------*/ BOOL Connect(HWND hWnd) { PWNDDATA pwd = {0}; COMMTIMEOUTS timeOut = {0}; DWORD dwThreadid = 0; DWORD i = 0; COMMCONFIG cc = {0}; pwd = (PWNDDATA) GetWindowLongPtr(hWnd, 0); // open serial port pwd->hPort = CreateFile(pwd->lpszCommName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if (pwd->hPort == INVALID_HANDLE_VALUE) { if (GetLastError() == ERROR_FILE_NOT_FOUND) { DISPLAY_ERROR("Serial port does not exist"); } else { DISPLAY_ERROR("Error opening port"); } return FALSE; } pwd->bConnected = TRUE; cc.dwSize = sizeof(COMMCONFIG); cc.wVersion = 1; GetCommConfig(pwd->hPort, &cc, &cc.dwSize); if (!CommConfigDialog(pwd->lpszCommName, hWnd, &cc)) { DISPLAY_ERROR("The comm settings dialogue failed.\nThis port may not exist"); } // set timeouts for the port if (!GetCommTimeouts(pwd->hPort, &timeOut)) { DISPLAY_ERROR("Error retrieving comm timeouts"); return FALSE; } timeOut.ReadIntervalTimeout = MAXDWORD; timeOut.ReadTotalTimeoutConstant = 0; timeOut.ReadTotalTimeoutMultiplier = 0; timeOut.WriteTotalTimeoutMultiplier = 0; timeOut.WriteTotalTimeoutConstant = 0; if (!SetCommTimeouts(pwd->hPort, &timeOut)) { DISPLAY_ERROR("Could not set comm timeouts"); return FALSE; } if (!SetCommState(pwd->hPort, &cc.dcb)) { DISPLAY_ERROR("Could not set comm state"); return FALSE; } // create thread for reading pwd->hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) PortIOThreadProc, hWnd, 0, &dwThreadid); if (pwd->hThread == INVALID_HANDLE_VALUE) { DISPLAY_ERROR("Error creating read thread"); return FALSE; } if (!EscapeCommFunction(pwd->hPort, SETRTS)) { DISPLAY_ERROR("Error sending RTS signal"); } if (!EscapeCommFunction(pwd->hPort, SETDTR)) { DISPLAY_ERROR("Error sending DTR signal"); } CUR_FG_COLOR = 7; CUR_BG_COLOR = 0; CUR_STYLE = 0; BRIGHTNESS = 0; // enable/disable appropriate menu choices EnableMenuItem(GetMenu(hWnd), IDM_DISCONNECT, MF_ENABLED); EnableMenuItem(GetMenu(hWnd), IDM_CONNECT, MF_GRAYED); EnableMenuItem(GetMenu(hWnd), IDM_COMMSET, MF_GRAYED); for (i = 0; i < NO_OF_PORTS; i++) { EnableMenuItem(GetMenu(hWnd), IDM_COM1 + i, MF_GRAYED); } return TRUE; }
HANDLE openPort(TCHAR * data) { HANDLE Port; //Дескриптор COM-порта //Открываем COM-порт Port = CreateFile(data, //Имя COM-порта GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (Port == INVALID_HANDLE_VALUE) { MessageBox(NULL, TEXT("Невозможно открыть последовательный порт"), TEXT("Error"), MB_OK); return 0; } //Получаем состояние управляющей структуры COM-порта, //если не удалось выводим сообщение об ошибке и выходим из //обработчика COMMCONFIG comm; GetCommState(Port, &comm.dcb); //Настраиваем управляющую структуру COM-порта comm.dcb.BaudRate=CBR_9600; comm.dcb.ByteSize = 8; //Размер байта comm.dcb.Parity = NOPARITY; //Паритет отключен comm.dcb.StopBits = ONESTOPBIT;//Один стоповый бит //Можно также воспользоваться стандартным диалоговым //окном настройки управляющей структуры COM-порта: CommConfigDialog(data,NULL,&comm); //Применяем настроенную структуру к COM-порту, если не //удалось выводим сообщение об ошибке if(!SetCommState(Port, &comm.dcb)) { MessageBox(NULL, TEXT("Невозможно сконфигурировать последовательный порт"), TEXT("Error"), MB_OK); CloseHandle(Port); return 0; } //Получаем текущие настройки тайм-аутов COM-порта COMMTIMEOUTS commTimeouts; GetCommTimeouts(Port, &commTimeouts); //Перенастраиваем тайм-ауты: //Максимальный интервал чтения в миллисекундах между //двумя принимаемыми символами commTimeouts.ReadIntervalTimeout = 100; //100 //Константа в миллисекундах используемая для вычисления //полного тайм-аута операции чтения commTimeouts.ReadTotalTimeoutConstant = 300; // 300 //Множитель используемый для вычисления полного тайм-аута //операции чтения в миллисекундах commTimeouts.ReadTotalTimeoutMultiplier = 50; //50 //Полный максимальный тайм-аут операции чтения //вычисляется следующим образом //ReadTotalTimeoutConstant + (ReadIntervalTimeout * количество считываемых байт) //Устанавливаем тайм-ауты для COM-порта if(!SetCommTimeouts(Port,&commTimeouts)) { MessageBox(NULL, TEXT("Невозможно настроить тайм-ауты последовательного порта"), TEXT("Error"), MB_OK); CloseHandle(Port); return 0; } return Port; }
LRESULT CALLBACK WndProc (HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { int response; HDC hdc; PAINTSTRUCT paintstruct; static unsigned k = 0; switch (Message) { case WM_COMMAND: switch (LOWORD (wParam)) { case IDM_COM1: cc.dwSize = sizeof(COMMCONFIG); cc.wVersion = 0x100; GetCommConfig (hComm, &cc, &cc.dwSize); if (!CommConfigDialog (lpszCommName, hwnd, &cc)) break; break; case IDM_COM2: cc.dwSize = sizeof(COMMCONFIG); cc.wVersion = 0x100; GetCommConfig (hComm, &cc, &cc.dwSize); if (!CommConfigDialog (lpszCommName, hwnd, &cc)) break; break; } break; case WM_RBUTTONDOWN: // Process right button response = MessageBox (hwnd, "Press One:", "Right Button", MB_ABORTRETRYIGNORE); switch (response) { case IDABORT: MessageBox (hwnd, "", "Abort", MB_OK); break; case IDRETRY: MessageBox (hwnd, "", "Retry", MB_OK); break; case IDIGNORE: MessageBox (hwnd, "", "Ignore", MB_OK); break; } break; case WM_LBUTTONDOWN: // Process left button response = MessageBox (hwnd, "Conitnue?", "Left Button", MB_ICONHAND | MB_YESNO); switch (response) { case IDYES: MessageBox (hwnd, "Press Button", "Yes", MB_OK); break; case IDNO: MessageBox (hwnd, "Press Button", "No", MB_OK); break; } break; case WM_CHAR: // Process keystroke hdc = GetDC (hwnd); // get device context sprintf (str, "%c", (char) wParam); // Convert char to string TextOut (hdc, 10*k, 0, str, strlen (str)); // output character k++; // increment the screen x-coordinate ReleaseDC (hwnd, hdc); // Release device context break; case WM_PAINT: // Process a repaint message hdc = BeginPaint (hwnd, &paintstruct); // Acquire DC TextOut (hdc, 0, 0, str, strlen (str)); // output character EndPaint (hwnd, &paintstruct); // Release DC break; case WM_DESTROY: // Terminate program PostQuitMessage (0); break; default: return DefWindowProc (hwnd, Message, wParam, lParam); } return 0; }
/*------------------------------------------------------------------------------ -- FUNCTION: PerformMenuAction -- -- DATE: Oct 19, 2010 -- -- REVISIONS: Dec 02, 2010 - added a case for opening a transmit file -- -- DESIGNER: Dean Morin -- -- PROGRAMMER: Dean Morin -- -- INTERFACE: VOID PerformMenuAction(HWND hWnd, WPARAM wParam) -- hWnd - the handle to the window -- wParam - contains the menu item that was selected -- -- RETURNS: VOID. -- -- NOTES: -- Responds to a user's selection of a menu item. ------------------------------------------------------------------------------*/ VOID PerformMenuAction(HWND hWnd, WPARAM wParam) { PWNDDATA pwd = NULL; DWORD dwSize = 0; COMMCONFIG cc = {0}; pwd = (PWNDDATA) GetWindowLongPtr(hWnd, 0); switch (LOWORD(wParam)) { case IDM_CONNECT: if(OpenFileReceive(hWnd)) { Connect(hWnd); ShowWindow(pwd->hDlgStats, SW_NORMAL); ShowWindow(pwd->hDlgDebug, SW_NORMAL); } return; case IDM_DISCONNECT: Disconnect(hWnd); CloseFileReceive(hWnd); CloseFileTransmit(hWnd); return; case IDM_EXIT: PostMessage(hWnd, WM_DESTROY, 0, 0); return; case IDM_COM1: case IDM_COM2: case IDM_COM3: case IDM_COM4: case IDM_COM5: case IDM_COM6: case IDM_COM7: case IDM_COM8: case IDM_COM9: SelectPort(hWnd, LOWORD(wParam)); return; case IDM_COMMSET: cc.dwSize = sizeof(COMMCONFIG); cc.wVersion = 1; GetCommConfig(pwd->hPort, &cc, &cc.dwSize); if (!CommConfigDialog(pwd->lpszCommName, hWnd, &cc)) { DISPLAY_ERROR("The comm settings dialogue failed.\nThis port may not exist"); } return; case IDM_STATISTICS: ShowWindow(pwd->hDlgStats, SW_NORMAL); return; case IDM_DEBUGGER: ShowWindow(pwd->hDlgDebug, SW_NORMAL); return; case ID_OPEN_TRANSMITFILE: OpenFileTransmit(hWnd); return; default: return; } }
/*------------------------------------------------------------------------------------------------------------------ -- FUNCTION: WndProc -- DATE: September 21st, 2012 -- REVISIONS: n/a -- DESIGNER: Ramzi Chennafi -- PROGRAMMER: Ramzi Chennafi -- -- INTERFACE: LRESULT CALLBACK WndProc (HWND hwnd, UINT Message, -- WPARAM wParam, LPARAM lParam) -- -- RETURNS: LRESULT to the system. -- -- NOTES: -- Deals with the main window thread. Requests writes, modification of data settings, usage information and -- connect/disconnect buttons. Also creates a new thread to perform read operations. ----------------------------------------------------------------------------------------------------------------------*/ LRESULT CALLBACK WndProc (HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { HMENU menuHnd = GetMenu(hwnd); switch (Message) { case WM_COMMAND: switch (LOWORD (wParam)) { case IDM_CONNECT: if(!io->serialOn){ if((io->hdSerial = init(io)) != NULL){ MessageBox (hwnd, TEXT("Client Connected"), TEXT("Dumb Terminal"), MB_OK | MB_ICONEXCLAMATION); io->serialOn = true; io->readThrd = CreateThread(NULL, 0, execRead, io, 0, &io->threadId); EnableMenuItem(menuHnd, IDM_CONNECT, MF_GRAYED); DrawMenuBar(hwnd); } } break; case IDM_HELP: MessageBox (hwnd, TEXT("Choose which port you wish to communicate on and then hit data settings to modify the communication settings.\nConnect will begin a session, hit escape to end the current session.\nAny keyboard input will be transferred during a session."), TEXT("Dumb Terminal"), MB_OK | MB_ICONINFORMATION); break; case ID_PORT_COMM1: io->port = TEXT("com1"); checkItem(menuHnd, COMM1); break; case ID_PORT_COMM3: io->port = TEXT("com3"); checkItem(menuHnd, COMM3); break; case IDM_DATA_SETTINGS: io->cc.dwSize = sizeof(COMMCONFIG); io->cc.wVersion = 0x100; GetCommConfig (hComm, &io->cc, &io->cc.dwSize); if (!CommConfigDialog (io->port, io->hwnd, &io->cc)) break; break; } break; case WM_CHAR: if(io->serialOn && wParam != VK_ESCAPE){ writeOutputBuffer(io->hdSerial, wParam); } break; case WM_KEYDOWN: if(wParam == VK_ESCAPE && io->serialOn == true){ io->serialOn = false; MessageBox (hwnd, TEXT("Client Disconnected"), TEXT("Dumb Terminal"), MB_OK | MB_ICONEXCLAMATION); InvalidateRect(hwnd, NULL, FALSE); EnableMenuItem(menuHnd, IDM_CONNECT, MF_ENABLED); DrawMenuBar(hwnd); endSession(io->hdSerial, io->readThrd); } break; case WM_DESTROY: PostQuitMessage (0); break; default: return DefWindowProc (hwnd, Message, wParam, lParam); } return 0; }