BOOL CComm::OpenComm(int n, int baud, int parity, int databits, int stopbits)
{
CString str = _T("");
str.Format("COM%d", n);
if((m_hcomm = CreateFile(str, 
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
NULL)) != INVALID_HANDLE_VALUE)
{
SetComm(baud, parity, databits, stopbits);
SetTimeout(250);
return TRUE;
}
DWORD dwerr = GetLastError();
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwerr, 0, str.GetBufferSetLength(80), 80, NULL);
AfxMessageBox(str, MB_OK | MB_ICONEXCLAMATION, 0);
str.ReleaseBuffer(0);
return FALSE;
}void CComm::SetComm(int baud, int parity, int databits, int stopbits)
{
DCB dcb;
::GetCommState(m_hcomm, &dcb);
if(baud != -1)dcb.BaudRate = baud;
if(parity != -1)dcb.Parity = parity;
if(databits != -1)dcb.ByteSize = databits;
if(stopbits != -1)dcb.StopBits = stopbits;
::SetCommState(m_hcomm, &dcb);
}DWORD CComm::WriteComm(LPSTR lpbuf, int len)
{
DWORD dwnum;
BOOL bSuccess;
//COMSTAT   ComStat; 
         //DWORD   dwError=0;
//bSuccess =  ClearCommError(m_hcomm,&dwError,&ComStat);
bSuccess =  WriteFile(m_hcomm, lpbuf, (DWORD)len, &dwnum, NULL);
//DWORD dwerr = GetLastError();
//if (dwerr == ERROR_IO_PENDING) 
//{
// int i = 0;
//}
return dwnum;
}DWORD CComm::SetTimeout(DWORD dwtime)
{
COMMTIMEOUTS cto;
::GetCommTimeouts(m_hcomm, &cto);
DWORD dwret = cto.ReadTotalTimeoutConstant;
cto.ReadIntervalTimeout = 0;
cto.ReadTotalTimeoutConstant = dwtime;
cto.ReadTotalTimeoutMultiplier = 0;
cto.WriteTotalTimeoutConstant = 0;
cto.WriteTotalTimeoutMultiplier = 0;
::SetCommTimeouts(m_hcomm, &cto);
return dwret;
}
以上代码 设置部分没问题 ,就是WriteFile始终不成功,到底怎么回事??

解决方案 »

  1.   

    设置超时时间,否则可能是默认的值,那就有可能超时反回了吧,关键你是同步的ReadFile函数只要在串行口输入缓冲区中读入指定数量的字符,就算完成操作。
    而WriteFile函数不但要把指定数量的字符拷入到输出缓冲中,而且要等这些字符从串行口送出去后才算完成操作。
    改改下面的超时函数
    COMMTIMEOUTS timeOver;
    memset(&&timeOver.0.sizeof(timeOver));
    DWORDtimeMultiplier,timeConstant;
    timeOver.ReadTotalTimeoutMultiplier=timeMultiplier;
    timeOver.ReadTotalTimeoutConstant=timeConstant;
    SetCommTimeouts(hComport,&&timeOver);
      

  2.   

    问题已找到。不过还是要感谢楼上的,关键在于 CreateFile的时候指定了异步通讯,WriteFile跟ReadFile的最后一个参数都不能输NULl。