界面布局
//打开串口
void CMSCommDlg::OnButtonOpen()
{
// TODO: Add your control notification handler code here
if(m_mscomm.GetPortOpen())
{
m_mscomm.SetPortOpen(FALSE);
}
m_mscomm.SetCommPort(1);//设置串口号为com1
m_mscomm.SetOutBufferSize(1024);//设置输出缓存区大小为1024字节
m_mscomm.SetInBufferSize(1024);//设置输入缓存区大小为1024字节
m_mscomm.SetInputMode(1);//设置输入方式为二进制
m_mscomm.SetSettings("9600,n,8,1");//设置传输的波特率,奇偶校检位,数据位,结束位
m_mscomm.SetRThreshold(1);//接收到一个字符就触发事件
m_mscomm.SetInputLen(0);
if(!m_mscomm.GetPortOpen())
{
m_mscomm.SetPortOpen(TRUE);
AfxMessageBox("串口打开成功");
}
else{
AfxMessageBox("串口打开失败");
}
}
//关闭串口
void CMSCommDlg::OnButtonClose()
{
// TODO: Add your control notification handler code here
m_mscomm.SetPortOpen(FALSE);
AfxMessageBox("串口关闭成功");
}
//发送消息
void CMSCommDlg::OnButtonSend()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
if(!m_mscomm.GetPortOpen())
{
AfxMessageBox("请先打开串口");
}
else{
WORD length;
length=m_send.GetLength();
CByteArray sendArr;
sendArr.SetSize(length);
for (int i=0;i<length;i++)
{
sendArr.SetAt(i,m_send.GetAt(i));
}
m_mscomm.SetOutput(COleVariant(sendArr));
}
}
//comm事件处理函数
void CMSCommDlg::OnOnCommMscomm1()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
VARIANT variant_input;
COleSafeArray safearry_input;
char inputdata[1024];
switch(m_mscomm.GetCommEvent())
{
case 2:
variant_input=m_mscomm.GetInput();
safearry_input=variant_input;
int len=safearry_input.GetOneDimSize();
for (long i=0;i<len;i++)
{
safearry_input.GetElement(&i,&inputdata[i]);
}
inputdata[i]='\0';
m_recv+=inputdata;
UpdateData(FALSE);
break;
}
}