DWORD WINAPI ReadPortThread(LPVOID lpvoid)
{
         BYTE Byte;
DWORD dwCommModemStatus,
dwBytesTransferred;
CString tempStr;
  
// Specify a set of events to be monitored for the port.
SetCommMask (hPort, EV_RXCHAR);
         
         WaitCommEvent (hPort, &dwCommModemStatus, 0);
         if (dwCommModemStatus & EV_RXCHAR) 
         {
              do 
    {
tempStr=TEXT("");
// Read the data from the serial port.
ReadFile (hPort, &Byte, 1, &dwBytesTransferred, 0); // Display the data read.
if (dwBytesTransferred == 1)
{
tempStr=(char)Byte;
strInStr+=tempStr;
}      }while (dwBytesTransferred == 0);
  MessageBox(NULL,strInStr,TEXT("Result"),MB_OK);
       } // Retrieve modem control-register values.
GetCommModemStatus (hPort, &dwCommModemStatus);
}则无论我发几个字符都只能收到第一个,要是改为:
DWORD WINAPI ReadPortThread(LPVOID lpvoid)
{
         BYTE Byte;
DWORD dwCommModemStatus,
dwBytesTransferred;
CString tempStr;
  
// Specify a set of events to be monitored for the port.
SetCommMask (hPort, EV_RXCHAR);
         
         WaitCommEvent (hPort, &dwCommModemStatus, 0);
         if (dwCommModemStatus & EV_RXCHAR) 
         {
              DWORD length=0;
     COMSTAT ComStat;
     DWORD dwErrorFlags;
     char *buf=NULL;
     ClearCommError(hPort,&dwErrorFlags,&ComStat);
     length=ComStat.cbInQue;
     ReadFile(hPort,buf,length,&length,NULL);      CString temp=buf;
     MessageBox(NULL,temp,TEXT("Result"),MB_OK);
       } // Retrieve modem control-register values.
GetCommModemStatus (hPort, &dwCommModemStatus);
}
则消息框里为空。
各位帮帮忙,看看是什么问题啊。

解决方案 »

  1.   

    第一个:
      tempStr=(char)Byte;
     应写成
      tempStr.Format("%c",Byte);第二个:
      CString temp=buf;
    应写为:
      CString temp;
      temp.Format("%s",buf);
    不要想用 CString对象=char指针来拷贝字符串
    一定要用Format
      

  2.   

    把你的程序改为下面的看看DWORD WINAPI ReadPortThread(LPVOID lpvoid)
    {
             BYTE Byte;
    DWORD dwCommModemStatus,
    dwBytesTransferred;
    CString tempStr;
             char *buf=new char[4096];//接收缓冲区不能为NULL,否则怎能接收数据?
             TCHAR * temp=buf;
             DWORD length=0;
             COMSTAT ComStat;
             DWORD dwErrorFlags;
    // Specify a set of events to be monitored for the port.
    SetCommMask (hPort, EV_RXCHAR);
             for(;;)
    {
             WaitCommEvent (hPort, &dwCommModemStatus, 0);
             if (dwCommModemStatus & EV_RXCHAR) 
             {
         ClearCommError(hPort,&dwErrorFlags,&ComStat);
         length=ComStat.cbInQue;
         ReadFile(hPort,buf,length,&length,NULL);
                  *(temp+length)=0;
         AfxMessageBox(temp);
           }
    }
    // Retrieve modem control-register values.
    GetCommModemStatus (hPort, &dwCommModemStatus);
    }