我正在尝试编写使用串行端口(例如COM8)的C++ MFC应用程序。每次我尝试设置DCB时都会失败。如果有人能指出我做错了什么,我会非常感激。尝试配置COM端口时设置DCB失败
DCB dcb = {0};
dcb.DCBlength = sizeof(DCB);
port.Insert(0, L"\\\\.\\");
m_hComm = CreateFile(
port, // Virtual COM port
GENERIC_READ | GENERIC_WRITE, // Access: Read and write
0, // Share: No sharing
NULL, // Security: None
OPEN_EXISTING, // The COM port already exists.
FILE_FLAG_OVERLAPPED, // Asynchronous I/O.
NULL // No template file for COM port.
);
if (m_hComm == INVALID_HANDLE_VALUE)
{
TRACE(_T("Unable to open COM port."));
ThrowException();
}
if (!::GetCommState(m_hComm, &dcb))
{
TRACE(_T("CSerialPort : Failed to get the comm state - Error: %d"), GetLastError());
ThrowException();
}
dcb.BaudRate = 38400; // Setup the baud rate.
dcb.Parity = NOPARITY; // Setup the parity.
dcb.ByteSize = 8; // Setup the data bits.
dcb.StopBits = 1; // Setup the stop bits.
if (!::SetCommState(m_hComm, &dcb)) // <- Fails here.
{
TRACE(_T("CSerialPort : Failed to set the comm state - Error: %d"), GetLastError());
ThrowException();
}
谢谢。
附加信息:生成的错误代码是87:“该参数不正确。” 可能是微软的大多数有用的错误代码。 j/k
您可以提及错误代码。 – Amnon 2010-11-15 21:05:39
@Amnon:好的,我将错误代码信息添加到了我原来的帖子中,但我认为它没有多大帮助。 – 2010-11-15 21:09:00