VC(MFC)编写串口调试助手

编辑代码如下:

void CCommassistDlg::OnClose() { // TODO: Add your message handler code here and/or call default TerminateThread(pReceiveThread,0); //程序退出时,关闭串口监听线程 WaitForSingleObject(pReceiveThread,INFINITE); CDialog::OnClose(); }

双击“手动发送”按钮,编辑代码如下: UINT CCommassistDlg::OnBtnHandsend() { // TODO: Add your control notification handler code here if(ComIsOK == FALSE) { MessageBox(\请先打开串口\提示\TION); return 0; } BOOL bWriteStat; UpdateData(TRUE); CString str,sTemp; DWORD dwBytesWritten=1024; OVERLAPPED m_osWrite; memset(&m_osWrite,0,sizeof(OVERLAPPED)); m_osWrite.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL); COMSTAT ComStat;

第 29 页 共 37 页

DWORD dwErrorFlags;

// dwBytesWritten = OnCheckHextx(); GetDlgItem(IDC_EDIT_TX)-> GetWindowText(strOut); if(m_check_hextx) { int i,n; CString strTemp; CByteArray hexdata; // GetDlgItem(IDC_EDIT_TX)-> GetWindowText(strOut); dwBytesWritten = ConvertHexC2String(strOut,hexdata); n = hexdata.GetSize(); for(i=0;i GetWindowText(str); SetDlgItemText(IDC_EDIT_TX,\ sTemp = DisplayHex2CString(str); dwBytesWritten = str.GetLength(); SetDlgItemText(IDC_EDIT_TX,strOut); } UpdateData(); if(dwBytesWritten==0) { MessageBox(\请在发送区内输入要发送的内容\提示\ return 0; } m_intTxCnt += dwBytesWritten; ShowStatus(); ClearCommError(hCom,&dwErrorFlags,&ComStat); bWriteStat=WriteFile(hCom,strOut,dwBytesWritten,&dwBytesWritten,&m_osWrite); if(!bWriteStat) { if(GetLastError()==ERROR_IO_PENDING) { WaitForSingleObject(m_osWrite.hEvent,1000);

第 30 页 共 37 页

return dwBytesWritten; } return 0; } ShowStatus(); PurgeComm(hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); return dwBytesWritten; }

编辑ShowStatus函数,代码如下: void CCommassistDlg::ShowStatus() { //状态栏显示状态 CString strTXcnt; CString strRXcnt; CString sTemp; CString comnum; CString strBaud,strStop,strData,strCal; UpdateData(true); if(ComIsOK) { m_comlist.GetLBText(m_comlist.GetCurSel(),sTemp); comnum = sTemp + \已打开\ } else comnum=\未打开串口\ strTXcnt.Format(\发送:%d\ strRXcnt.Format(\接收:%d\ m_baud.GetLBText(m_baud.GetCurSel(),strBaud); m_bstop.GetLBText(m_bstop.GetCurSel(),strStop); m_bdata.GetLBText(m_bdata.GetCurSel(),strData); m_cal.GetLBText(m_cal.GetCurSel(),strCal); m_strStatus = \串口: \ \状态: \波特率: \ + \数据位: \停止位: \校验位: \+ strCal; UpdateData(FALSE); }

双击“清空显示区”按钮,编辑代码如下: void CCommassistDlg::OnBtnClrrx() { // TODO: Add your control notification handler code here GetDlgItem(IDC_EDIT_RX);

第 31 页 共 37 页

SetDlgItemText(IDC_EDIT_RX,\ m_intRxCnt = 0; m_intTxCnt = 0; strIn = \ ShowStatus(); }

双击“清空发送区”按钮,编辑代码如下: void CCommassistDlg::OnBtnClrtx() { // TODO: Add your control notification handler code here GetDlgItem(IDC_EDIT_TX); SetDlgItemText(IDC_EDIT_TX,\}

添加WM_TIMER定时器

OnTimer函数代码如下:

void CCommassistDlg::OnTimer(UINT nIDEvent) { // TODO: Add your message handler code here and/or call default if(nIDEvent == 1) OnBtnHandsend(); else if(nIDEvent == 2) return; CDialog::OnTimer(nIDEvent); }

第 32 页 共 37 页

联系客服:779662525#qq.com(#替换为@)