|
读线程代码:
- DWORD WINAPI ReadCommThread(LPARAM lparam)///读线程
- {
- extern charCount;
- extern HANDLE m_hCom;
- extern OpenCloseFlag;
- extern unsigned char pszRecv[1024];
- DWORD ReadBytes;
- DWORD bResult;
- DWORD dwErr;
- OVERLAPPED ReadOver;
- DWORD hMask;
- DWORD CommEvent;
- int i=0;
- CRITICAL_SECTION section;
- COMSTAT comstat;
- DWORD Flag=0;
- memset(&ReadOver,0x00,sizeof(ReadOver));
- ReadOver.Offset=0;
- ReadOver.OffsetHigh=0;
- ReadOver.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);
- PurgeComm(m_hCom,PURGE_TXABORT | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_RXCLEAR);
- InitializeCriticalSection(§ion);
-
- for(;;)
- {
- bResult=WaitCommEvent(m_hCom,&hMask,&ReadOver);
- if(OpenCloseFlag==1) //串口已被打开才做下一部
- {
- if(!bResult)
- {
- switch(dwErr=GetLastError())
- {
- case ERROR_IO_PENDING:
-
- // MessageBox(NULL,"读取成功",0,MB_OK);
- Flag^=1;
- break;
- /* case 87:
-
- break;*/
- default:
- SetDlgItemText((HWND)lparam,IDC_COMMSTATE,"WaitCommEvent Error");
- goto ErrorNext;
- }
- }else
- {
- bResult=ClearCommError(m_hCom,&dwErr,&comstat);
- if(comstat.cbInQue==0)
- continue;
- }
- WaitForSingleObject(ReadOver.hEvent,INFINITE);///等侍异步操作完成
- Flag=0;
- //ResetEvent(ReadOver.hEvent);////设置为不发信号状态
- GetCommMask(m_hCom,&hMask);
- if(hMask & EV_CTS)//CTS信号改变
- {
- }
- if(hMask & EV_RXFLAG)//收到特殊字符
- {
- }
- if(hMask & EV_BREAK)
- {
- }
- if(hMask & EV_ERR)//端口错误信号
- {
- }
- if(hMask & EV_RING) //ring信号变化
- {
- }
-
- if(hMask & EV_RXCHAR)///收到一个或多个字符
- {
-
- EnterCriticalSection(§ion);
- bResult=ClearCommError(m_hCom,&dwErr,&comstat);
- if(!ReadFile(m_hCom,pszRecv,1024,&ReadBytes,&ReadOver))
- {
- switch(dwErr=GetLastError())
- {
- case ERROR_IO_PENDING:
- Flag^=1;
- break;
- default:
- goto ErrorNext;
- }
- }
- if(Flag & 1)
- {
-
- SetDlgItemText((HWND)lparam,IDC_COMMSTATE,"正在读取数据");
-
- WaitForSingleObject(ReadOver.hEvent,INFINITE);
- if(GetOverlappedResult(m_hCom,&ReadOver,&ReadBytes,TRUE))
- {
- SetDlgItemText((HWND)lparam,IDC_COMMSTATE,"读取数据完成");
- SetDlgItemText((HWND)lparam,IDC_SHOWINFO,pszRecv);
- }
- }
- LeaveCriticalSection(§ion);
- }
- ErrorNext:
- Flag=0;
- PurgeComm(m_hCom,PURGE_TXABORT | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_RXCLEAR);
- }
-
- }
- return 1;
- }
复制代码 |
|