见:http://blog.csdn.net/flydream0/article/details/8002012
右击MSComm控件,然后选择Add Variable...
右击MSComm控件,然后选择Add Event Handle..
void Ctbox_debug_viewDlg::OnBnClickedBtOpen() { // TODO: Add your control notification handler code here if(m_mscomm.get_PortOpen()) { m_mscomm.put_PortOpen(FALSE); GetDlgItem(IDC_BT_OPEN)->SetWindowText(_T("打开")); ShowInfo(_T("关闭串口成功!")); m_OpenStatus =false; return; } UpdateData(TRUE); m_OpenStatus =true; //当前端口号 m_mscomm.put_CommPort(m_Port+1);//端口号 m_mscomm.put_InBufferSize(1024);//接收缓冲区 m_mscomm.put_OutBufferSize(1024);//发送缓冲区 m_mscomm.put_InputLen(0);//设置当前接收区数据长度为0,表示全部读取 m_mscomm.put_InputMode(1);//以二进制方式读写数据 m_mscomm.put_RThreshold(1);//接收缓冲区有1个及1个以上字符时,将引发接收数据的OnComm事件 //波特率 DWORD baudrate; switch(m_CombolBaudrate.GetCurSel()) { case 0: baudrate =115200; break; case 1: baudrate =9600; break; default: ASSERT(FALSE); break; } CString setting; setting.Format(_T("%d,n,8,1"),baudrate); m_mscomm.put_Settings(setting/*_T("115200,n,8,1")*/);//波特率,无校验,8个数据位,1个停止1位 m_mscomm.put_PortOpen(TRUE);//打开串口 GetDlgItem(IDC_BT_OPEN)->SetWindowText(_T("关闭")); ShowInfo(_T("打开串口成功!")); }
void Ctbox_debug_viewDlg::OnCommMscomm1() { // TODO: Add your message handler code here short curEvent =m_mscomm.get_CommEvent(); switch(curEvent) { case CMscomm1::comEvReceive: EvReceiveHandle(); break; } }
void Ctbox_debug_viewDlg::EvReceiveHandle(void) { static unsigned int cnt=0; VARIANT variant_inp; COleSafeArray safearray_inp; long len,k; /*unsigned intdata[1024]={0};*/ BYTE rxdata[1024];//设置BYTE数组 CString strtemp; cnt++; variant_inp= m_mscomm.get_Input();//读取缓冲区 safearray_inp= variant_inp;//变量转换 len= safearray_inp.GetOneDimSize();//得到有效的数据长度 for (k=0;k<len;k++) { safearray_inp.GetElement(&k,rxdata+k); } /*char c_char; */ for (k=0;k<len;k++) { strtemp.Format(_T("%c"),*(rxdata+k)); m_RecveString +=strtemp; if(*(rxdata+k) =='\n') { ShowInfoByFilter(m_RecveString); m_RecveString =""; } } }
void Ctbox_debug_viewDlg::OnBnClickedBtSend() { // TODO: Add your control notification handler code here if(m_OpenStatus ==false) { AfxMessageBox(_T("请先打开串口")); return; } UpdateData(TRUE); if(m_SendString.IsEmpty()) return; if(m_AutoAddLF) { m_SendString +="\r\n"; } m_mscomm.put_Output(COleVariant(m_SendString)); ShowInfo(m_SendString); }