reading from serial port
-
Hi, OS:Win2000 using VC++ .NET 2003 I have some sample code (from msdn) to read and write to the serial port. The code works perfectly when I put it into a console program. However, when I put excactly the same code into an Windows Form Application the program "hangs" at the reading routines. Do other reading routines apply to Windows Forms Applications? I simply can´t understand why it doesn´t work...
BYTE Byte; DWORD dwBytesTransferred; // Specify a set of events to be monitored for the port. SetCommMask (hPort, EV_RXCHAR | EV_CTS | EV_DSR | EV_RLSD | EV_RING); while (hPort != INVALID_HANDLE_VALUE) { // Wait for an event to occur for the port. WaitCommEvent (hPort, &dwCommModemStatus, 0); // Re-specify the set of events to be monitored for the port. SetCommMask (hPort, EV_RXCHAR | EV_CTS | EV_DSR | EV_RING); if (dwCommModemStatus & EV_RXCHAR) { // Loop for waiting for the data. do { // Read the data from the serial port. ReadFile (hPort, &Byte, 1, &dwBytesTransferred, 0); // Display the data read. if (dwBytesTransferred == 1) this->label1->Text = S"string"; } while (dwBytesTransferred == 1); }
-
Hi, OS:Win2000 using VC++ .NET 2003 I have some sample code (from msdn) to read and write to the serial port. The code works perfectly when I put it into a console program. However, when I put excactly the same code into an Windows Form Application the program "hangs" at the reading routines. Do other reading routines apply to Windows Forms Applications? I simply can´t understand why it doesn´t work...
BYTE Byte; DWORD dwBytesTransferred; // Specify a set of events to be monitored for the port. SetCommMask (hPort, EV_RXCHAR | EV_CTS | EV_DSR | EV_RLSD | EV_RING); while (hPort != INVALID_HANDLE_VALUE) { // Wait for an event to occur for the port. WaitCommEvent (hPort, &dwCommModemStatus, 0); // Re-specify the set of events to be monitored for the port. SetCommMask (hPort, EV_RXCHAR | EV_CTS | EV_DSR | EV_RING); if (dwCommModemStatus & EV_RXCHAR) { // Loop for waiting for the data. do { // Read the data from the serial port. ReadFile (hPort, &Byte, 1, &dwBytesTransferred, 0); // Display the data read. if (dwBytesTransferred == 1) this->label1->Text = S"string"; } while (dwBytesTransferred == 1); }
Your main thread is blocking on the WaitCommEvent. Typically, code like this would be placed into a separate tread where it would not interfere with the processing of other information, such as mouse movements, painting, keyboard events, etc.