1.下载mscomm控件;
(下载地址:http://download.csdn.net/detail/tianhen791/4023983)
2.安装注册控件:下载完成后解压->点击setup.bat 即可此控件的安装和注册;
3.- 添加->COM组件->Mircrosoft Communications Control, version 6.0
- 拖mscomm拖至对话框,
- 添加变量 m_comm
- 添加事件 OnComm
- void CtestDlg::InitMsComm(void)
- {
- m_comm.put_CommPort(1); // 选择COM1
- m_comm.put_InBufferSize(1024); // 指定接收缓冲区大小
- m_comm.put_OutBufferSize(1024);// 指定发送缓冲区大小
- m_comm.put_InputLen(0); // 设置当前接收区数据长度为0,表示全部读取
- m_comm.put_InputMode(1); // 以二进制方式读写数据
- m_comm.put_Settings(L"9600,N,8,1"); // 波特率9600无检验位,8个数据位,1个停止位
- m_comm.put_RThreshold(1); // 接收缓冲区有1个及1个以上字符时,将引发接收数据的OnComm事件
- try
- {
- m_comm.put_PortOpen(TRUE);
- }
- catch (...)
- {
- AfxMessageBox(L"串口1打开失败");
- return;
- }
- m_comm.get_Input(); //先预读缓冲区以清除残留数据
- }
- void CtestDlg::OnCommMscomm1()
- {
- // ==============串口数据接收过程===================
- if(m_comm.get_CommEvent() == 2)
- {
- COleSafeArray SafeArray = m_comm.get_Input(); //第一步
- int iLen = SafeArray.GetOneDimSize(); //第二步
- BYTE revBuf[1024];
- for(long i = 0;i < iLen; i++)
- {
- SafeArray.GetElement(&i, revBuf + i);
- }
- //对revBuf进行自己的处理
- }
- }
- //================发送=================
- void CtestDlg::SendCommBuf(BYTE *pSendBuf, int count)
- {
- CByteArray m_Array;
- m_Array.SetSize(count);
- for(int i = 0; i < count; i++)
- {
- m_Array.SetAt(i, pSendBuf[i]);
- }
- m_comm.put_Output(COleVariant(m_Array));
- }
- void CtestDlg::OnBnClickedButton1()//发送示例
- {
- BYTE buf[3] = {0x11,0x12,0x13};
- SendCommBuf(buf, 3);
- }