I created a program with C++ wxWidgets Framework to read data from the serial port in Windows 7.
When the program is running and clicking the Read "Baca" button, the data will show in the textbox. But aftert that, the program cannot be stopped by clicking the Stop "Berhenti" button. Even the program hangs. How to make it stop when clicking then button and not hang the program?
//This is code for read serial button
bool m_Aborted;
void SerialPortFrame::OnbtnBacaSerialClick(wxCommandEvent& event)
{
m_Aborted = false;
HANDLE hComm;
hComm=CreateFileA("\\.\COM4",GENERIC_READ | GENERIC_WRITE, 0, NULL,OPEN_EXISTING,0,NULL );
BOOL Status;
DCB dcbSerialParams={0};
dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
Status=GetCommState(hComm,&dcbSerialParams);
dcbSerialParams.BaudRate=CBR_9600;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;
Status=SetCommState(hComm,&dcbSerialParams);
COMMTIMEOUTS timeouts={0};
timeouts.ReadIntervalTimeout=50;
timeouts.ReadTotalTimeoutConstant=50;
timeouts.ReadTotalTimeoutMultiplier=10;
timeouts.WriteTotalTimeoutConstant=50;
timeouts.WriteTotalTimeoutMultiplier=10;
Status=SetCommMask(hComm,EV_RXCHAR);
DWORD dwEventMask;
Status=WaitCommEvent(hComm,&dwEventMask,NULL);
char TempChar;
char SerialBuffer[256];
DWORD NoBytesRead;
int i=0;
do{
Status=ReadFile(hComm,&TempChar,sizeof(TempChar),&NoBytesRead,NULL);
SerialBuffer[i]=TempChar;
wxString mystring1;
mystring1<<SerialBuffer[i];
txtSerial->AppendText(mystring1.c_str());
i++;
wxMilliSleep(300);
wxThread::This()->Sleep(1);
} while(!m_Aborted);
CloseHandle(hComm);
}
//This is code for stop
void SerialPortFrame::OnbtnBerhentiClick(wxCommandEvent& event)
{
m_Aborted = true;
Close(true);
}
question from:
https://stackoverflow.com/questions/65871576/windows-applications-cannot-be-stopped-and-hangs 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…