//Call CreateFile to open up the comms port
CString sPort;
sPort.Format(_T("\\\\.\\%s"), szPort);
m_hComm = CreateFile(sPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, bOverlapped ? FILE_FLAG_OVERLAPPED : 0, NULL);
if (m_hComm == INVALID_HANDLE_VALUE)
{
sPort.Format("打开%s口失败", szPort);
MessageBox(NULL, sPort, _T("端口错误"), MB_OK);
}
//Create the event we need for later synchronisation use
m_hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (m_hEvent == NULL)
{
Close();
TRACE(_T("Failed in call to CreateEvent in Open\n"));
}
m_bOverlapped = bOverlapped;
//Get the current state prior to changing it
DCB dcb;
dcb.DCBlength = sizeof(DCB);
GetState(dcb);
//Setup the baud rate
dcb.BaudRate = dwBaud;
//Setup the Parity
switch (parity)
{
case EvenParity: dcb.Parity = EVENPARITY; break;
case MarkParity: dcb.Parity = MARKPARITY; break;
case NoParity: dcb.Parity = NOPARITY; break;
case OddParity: dcb.Parity = ODDPARITY; break;
case SpaceParity: dcb.Parity = SPACEPARITY; break;
default: ASSERT(FALSE); break;
}
//Setup the data bits
dcb.ByteSize = DataBits;
//Setup the stop bits
switch (stopbits)
{
case OneStopBit: dcb.StopBits = ONESTOPBIT; break;
case OnePointFiveStopBits: dcb.StopBits = ONE5STOPBITS; break;
case TwoStopBits: dcb.StopBits = TWOSTOPBITS; break;
default: ASSERT(FALSE); break;
}
//Now that we have all the settings in place, make the changes
SetState(dcb);
}
void CSerialPort::Close()
{
if (IsOpen())
{
//Close down the comms port
BOOL bSuccess = CloseHandle(m_hComm);
m_hComm = INVALID_HANDLE_VALUE;
if (!bSuccess)
TRACE(_T("Failed to close up the comms port, GetLastError:%d\n"), GetLastError());
m_bOverlapped = FALSE;
//Free up the event object we are using
CloseHandle(m_hEvent);
m_hEvent = NULL;
}
}
enum StopBits
{
OneStopBit,
OnePointFiveStopBits,
TwoStopBits
};
class CSerialPort
{
protected:
HANDLE m_hComm; //Handle to the comms port
HANDLE m_hEvent; //A event handle we need for internal synchronisation
BOOL m_bOverlapped; //Is the port open in overlapped IO
public:
enum FlowControl
{
NoFlowControl,
CtsRtsFlowControl,
CtsDtrFlowControl,
DsrRtsFlowControl,
DsrDtrFlowControl,
XonXoffFlowControl
};