代码如下:
void CGPSDlg::OnOnCommMscomm1()  
{
// TODO: Add your control notification handler code here
VARIANT m_varInput;
COleSafeArray m_oleInput;
BYTE rxdata[2048];
long length,i,j,k,ID;
CString str ,m_strCommData,strBuffer,str_Buffer;
int nHeadPos,nTailPos;
switch(m_Gpscomm.GetCommEvent())
{
case 2:
//MessageBox("数据");
//m_Gpscomm.SetRThreshold(0);//设置接收oncomm事件阈值
m_varInput = m_Gpscomm.GetInput();//读缓冲区
m_oleInput = m_varInput;//VARIANT变量转化为COleSafeArray变量
length = m_oleInput.GetOneDimSize();//得到有效数据长度
m_strCommData.Empty();
for(i = 0;i<length;i++)
m_oleInput.GetElement(&i,rxdata + i);//转换为BYTE型数组
for(k = 0;k < length;k++)//将数组转换为Cstring型变量
{
//char a = *(char*)(rxdata + k);//字符型
//str.Format("%c",a++);//将字符送入临时变量中存放BYTE bt = *(char*)(rxdata + k);//字符型str.Format("%d",bt);//将字符送入临时变量中存放
m_Gpsdlg_Richedit1.SetSel(1000000,1000000);
m_Gpsdlg_Richedit1.ReplaceSel(str);//显示字符
//m_Gpsdlg_Richedit1
str = str; 
UpdateData(FALSE);
  }
  }
 }
void CGPSDlg::OnInit()  
{
// TODO: Add your control notification handler code here
if(m_Gpscomm.GetPortOpen())//如果串口打开
m_Gpscomm.SetPortOpen(0);//关闭串行端口m_Gpscomm.SetCommPort(1);//设置端口1 
m_Gpscomm.SetSettings("4800,N,8,1");//获取当前串口通信参数
m_Gpscomm.SetInBufferSize(1024);//获取指定的接受缓冲区容量
m_Gpscomm.SetOutBufferSize(512);//获取指定的接受缓冲区容量
m_Gpscomm.SetInBufferCount(0);//清空接受缓冲区
m_Gpscomm.SetInputMode(1);//设置数据读取方式为二进制
m_Gpscomm.SetInputLen(0);//设置每次读取长度,0为全部读入
m_Gpscomm.SetRThreshold(1000);//设置接收oncomm事件阈值if(!m_Gpscomm.GetPortOpen())//如果关闭则打开
{
m_Gpscomm.SetPortOpen(1);//打开串行端口
MessageBox("初始化!");

else
AfxMessageBox("无法打开串口!");//m_Gpscomm.GetInput();//先预读缓冲区以清除残留数据
}void CGPSDlg::OnRecieve()  
{
// TODO: Add your control notification handler code hereif(m_Gpscomm.GetPortOpen() == TRUE)
{
m_Gpscomm.SetSettings("4800,N,8,1");//获取当前串口通信参数
m_Gpscomm.SetInputMode(1);//设置数据读取方式
m_Gpscomm.SetRThreshold(1000);//设置接收oncomm事件阈值
m_Gpscomm.SetInputLen(0);//设置每次读取长度,0为全部读入
m_Gpscomm.GetInput();//先预读缓冲区以清除残留数据
}
else
MessageBox("请初始化端口!");
}void CGPSDlg::OnStop()  
{
// TODO: Add your control notification handler code here
if(m_Gpscomm.GetPortOpen() == TRUE)
{
m_Gpscomm.SetPortOpen(0);//关闭串行端口
}
}

解决方案 »

  1.   

    m_Gpscomm.SetRThreshold(1);//设置接收oncomm事件阈值RThresholdSetting the RThreshold property to 0 (the default) disables generating the OnComm event when characters are received.
    Setting RThreshold to 1, for example, causes the Comm control to generate the OnComm event every time a single character is placed in the receive buffer.