if (!SetupComm (hCommDevice, COMM_PORT_BUFSIZE, COMM_PORT_BUFSIZE))
{
AfxMessageBox(L"SetupComm Failed!");
return FALSE;
}
//set comm port information
m_dcb.DCBlength = sizeof(DCB);
GetCommState (hCommDevice, &m_dcb);
m_dcb.BaudRate = 19200;
m_dcb.ByteSize = 8;
m_dcb.StopBits = ONESTOPBIT;
m_dcb.Parity = NOPARITY;
m_dcb.fBinary = TRUE;
m_dcb.fOutxDsrFlow = FALSE;
m_dcb.fDtrControl = DTR_CONTROL_ENABLE;
m_dcb.fRtsControl = (m_use_flow_ctrl) ? RTS_CONTROL_HANDSHAKE : RTS_CONTROL_ENABLE;
m_dcb.fOutxCtsFlow = m_use_flow_ctrl;
m_dcb.fOutX = FALSE;
m_dcb.fInX = FALSE;
m_dcb.fAbortOnError = TRUE;
m_dcb.XonLim = COMM_PORT_BUFSIZE * 2 / 3;
m_dcb.XoffLim = COMM_PORT_BUFSIZE / 3;
if (!SetCommState (hCommDevice, &m_dcb))
{
DWORD dwerror = GetLastError();
CString str;
str.Format(L"%d",dwerror);
MessageBox(str);
AfxMessageBox(L"SetCommState Failed!");
return FALSE;
}
//set comm port event
if (!SetCommMask (hCommDevice, (DWORD)(EV_RXCHAR | EV_CTS | EV_DSR | EV_RING | EV_RLSD)))
{
AfxMessageBox(L"SetCommMask Failed!");
return FALSE;
}
//set comm port read/write timeout
COMMTIMEOUTS cto;
memset (&cto, 0, sizeof (COMMTIMEOUTS));
cto.ReadIntervalTimeout = MAXDWORD;
if(!SetCommTimeouts (hCommDevice, &cto))
{
AfxMessageBox(L"SetCommTimeouts Failed!");
return FALSE;
}
return TRUE;
供参考,有些参数可能会不一样。