【更新】
按照各位的方法进行了内存初始化
现在不显示“烫烫烫“了 但也没有显示任何的字符是怎么回事呢?
这是执行到ReadFile语句时候的各个变量
但是再执行下一句的时候length就变为0了
而且str也是空的
在CString str(RXBuff);处断点显示:
麻烦各位了。。。
发送“123”的话就会显示一长串的烫
缓冲区也没清空
如果改成只接收单个字符的程序
也还是收到乱码
不管发送'1'还是'2'都显示‘Ì’
求指教~~
```struct Parameter
{
COMConfig* c;
CBLDDlg* dlg;
};
//这是开启的线程:
UINT ThreadFunc(LPVOID lpParam)
{
Parameter* parameter = (Parameter*)lpParam;
COMConfig* comConfig = parameter->c;
CBLDDlg* dlg = parameter->dlg;
BOOL bResult = TRUE;
DWORD Event = 0;
DWORD BytesTransfered = 0;
DWORD CommEvent = 0;
DWORD dwError = 0;
if(comConfig->m_hComm)
{
PurgeComm(comConfig->m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR);
}
else
{
AfxMessageBox(_T("串口初始化失败"));
return 0;
}
for(;;)
{
bResult = WaitCommEvent(comConfig->m_hComm,&Event,&(comConfig->m_ov));//监测通信事件
if(!bResult)
{
switch(dwError = GetLastError())
{
case ERROR_IO_PENDING:
{
AfxMessageBox(_T("正常"));
break;
}
case 87:
{
break;
}
default:
{
//显示错误信息
AfxMessageBox(_T("其他错误"));
break;
}
}
}
else
{
bResult = ClearCommError(comConfig->m_hComm,&dwError,&(comConfig->comstat));
if(comConfig->comstat.cbInQue == 0)//接收缓冲区字节数
continue;
}//end if bResult
Event = WaitForMultipleObjects(3,comConfig->m_hEventArray,FALSE,INFINITE);
switch(Event)
{
case 0:
{
//关闭串口操作
}
case 1:
{
GetCommMask(comConfig->m_hComm,&CommEvent);//获取当前通信事件
if(CommEvent & EV_RXCHAR)
dlg->ReceiveChar(comConfig,100);
AfxMessageBox(_T("读事件"));
break;
}
case 2:
{
//写数据操作
}
}
}
return 0;
}
然后下面是读数据的函数:
void CBLDDlg::ReceiveChar(LPVOID lpParam, DWORD dwLength)
{
BOOL bRead = TRUE;
BOOL bResult = TRUE;
DWORD dwError = 0;
COMConfig* comConfig = (COMConfig*)lpParam;
DWORD length = 0;
CString str;
char RXBuff[100];
InitializeCriticalSection(&cs);
for (;;)
{
EnterCriticalSection(&cs);
bResult = ClearCommError(comConfig->m_hComm, &dwError, &(comConfig->comstat));
LeaveCriticalSection(&cs);
if (comConfig->comstat.cbInQue == 0)
{
break;
}
EnterCriticalSection(&cs);
length=min(dwLength, comConfig->comstat.cbInQue);
if (bRead)
{
//读数据
bResult = ReadFile(comConfig->m_hComm, // Handle to COMM port
RXBuff, // RX Buffer Pointer
length, // Read one byte
&length, // Stores number of bytes read
&(comConfig->m_ov)); // pointer to the m_ov structure
CString str(RXBuff);
m_strEditReceiveMsg = str;
GetDlgItem(IDC_receive)->SetWindowText(str);//显示在控件中
if (!bResult)
{
switch (dwError = GetLastError())
{
case ERROR_IO_PENDING:
{
bRead = FALSE;
break;
}
default:
{
break;
}
}
}
else
{
bRead = TRUE;
}
} // close if (bRead)
if (!bRead)
{
bRead = TRUE;
bResult = GetOverlappedResult(comConfig->m_hComm, // Handle to COMM port
&(comConfig->m_ov), // Overlapped structure
&length, // Stores number of bytes read
TRUE); // Wait flag
if(!bResult)
{
AfxMessageBox(_T("GetOverlappedResults()in ReadFile()"));
}
SetCommMask(comConfig->m_ov.hEvent,EV_RXCHAR);//重置为有信号
LeaveCriticalSection(&cs);
}
}
}