void CSerialPort::WriteChar(CSerialPort* port)
{
BOOL bWrite = TRUE;
BOOL bResult = FALSE;

DWORD BytesSent = 0;

ResetEvent(port->m_hWriteEvent);

EnterCriticalSection(&port->m_csCommunicationSync);

if (bWrite)
{
PurgeComm(port->m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT); port->m_ov.Offset = 0;
port->m_ov.OffsetHigh = 0;

bResult = WriteFile(port->m_hComm, // Handle to COMM Port
port->m_szWriteBuffer, // Pointer to message buffer in calling finction
strlen(port->m_szWriteBuffer), // Length of message to send
&BytesSent, // Where to store the number of bytes sent
&port->m_ov); // Overlapped structur if (!bResult)
{
DWORD dwError = GetLastError();
switch (dwError)
{
case ERROR_IO_PENDING:
{
BytesSent = 0;
bWrite = FALSE;
break;
}
default:
{
port->ProcessErrorMessage("WriteFile()");
}
}
}
else
{
//AfxMessageBox("22222");
CString s;
s.Format("m_szWriteBuffer=%s",port->m_szWriteBuffer);
AfxMessageBox(s);
LeaveCriticalSection(&port->m_csCommunicationSync);
}
}
if (!bWrite)
{
bWrite = TRUE;

bResult = GetOverlappedResult(port->m_hComm, // Handle to COMM port 
&port->m_ov, // Overlapped structure
&BytesSent, // Stores number of bytes sent
TRUE);  // Wait flag LeaveCriticalSection(&port->m_csCommunicationSync);

if (!bResult)  
{
port->ProcessErrorMessage("GetOverlappedResults() in WriteFile()");
}
}
if (BytesSent != strlen((char*)port->m_szWriteBuffer))
{
TRACE("WARNING: WriteFile() error.. Bytes Sent: %d; Message Length: %d\n", BytesSent, strlen((char*)port->m_szWriteBuffer));
}
}
问题:这个发送返回值总是0,唉!找了半天也不知道为什么,更奇怪的是,我自发自收还能收到字符。服了,请大虾帮忙!!谢谢;
bResult = WriteFile(port->m_hComm, // Handle to COMM Port
port->m_szWriteBuffer, // Pointer to message buffer in calling finction
strlen(port->m_szWriteBuffer), // Length of message to send
&BytesSent, // Where to store the number of bytes sent
&port->m_ov);

解决方案 »

  1.   

    bResult = WriteFile(port->m_hComm, // Handle to COMM Port 
    port->m_szWriteBuffer, // Pointer to message buffer in calling finction 
    strlen(port->m_szWriteBuffer), // Length of message to send 
    &BytesSent, // Where to store the number of bytes sent 
    &port->m_ov); 
    //overlap方式,操作不等执行完毕就立即返回,用GetLastError()查看具体错误,如果是ERROR_IO_PENDING,则说明串口操作正在进行中。
      

  2.   

    http://msdn.microsoft.com/en-us/library/aa365747(VS.85).aspx
    函数问题,先查msdn