#define COM_RECVDATA WM_USER+1000 //自定义消息
afx_msg void OnRecvData(WPARAM wParam, LPARAM lParam); // 映射函数
BEGIN_MESSAGE_MAP(CSerialportapiDlg, CDialog) // 映射函数
//{{AFX_MSG_MAP(CSerialportapiDlg)
ON_MESSAGE(COM_RECVDATA ,OnRecvData)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
//打开串口完成配置
OpenSerialPort1();
//启动串口监视线程
DWORD threadID;
hCommThread = ::CreateThread((LPSECURITY_ATTRIBUTES)NULL, 0,
(LPTHREAD_START_ROUTINE)SerialPort1ThreadProcess, AfxGetMainWnd()->m_hWnd, 0, &threadID);
if (hCommThread == NULL)
{
::AfxMessageBox("创建串口1处理线程失败");
::PostQuitMessage(0);
}
HANDLE hCom; //全局变量,串口句柄
HANDLE hCommThread; //全局变量,串口线程
//DWORD WINAPI SerialPort1ThreadProcess( HWND hWnd);//串口监视线程函数
//BOOL OpenSerialPort1(); //打开并设置串口
BOOL OpenSerialPort1()
{
//打开并设置COM1
hCom=CreateFile("COM1", GENERIC_READ|GENERIC_WRITE, 0, NULL ,OPEN_EXISTING, 0,NULL);
if (hCom==(HANDLE)-1)
{
AfxMessageBox("打开COM1失败");
return false;
}
else
{
DCB wdcb;
GetCommState (hCom,&wdcb);
wdcb.BaudRate=9600;
SetCommState (hCom,&wdcb);
PurgeComm(hCom,PURGE_TXCLEAR);
}
return true;
}
//以一个线程不停监控串口行接收的数据
DWORD WINAPI SerialPort1ThreadProcess( HWND hWnd //主窗口句柄
)
{
char str[101];
DWORD wCount; //读取的字节数
while(1)
{
ReadFile(hCom, str, 100, &wCount, NULL);
if(wCount > 0) //接受数据
{
str[wCount] = '/0';
::PostMessage(hWnd, COM_RECVDATA, (unsigned int)str, wCount);
}
}
return TRUE;
}
void CSerialportapiDlg::OnRecvData(WPARAM wParam, LPARAM lParam)
{
CString recvStr((char *)wParam);
m_recv+=recvStr;
UpdateData(false);
m_recvedit.LineScroll(m_recvedit.GetLineCount()-1,0);
}