【发布时间】:2011-05-10 11:33:16
【问题描述】:
我正在尝试编写一个使用串行端口(例如 COM8)的 C++ MFC 应用程序。每次我尝试设置 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:好的,我在原始帖子中添加了错误代码信息,但我认为它没有多大帮助。
标签: c++ visual-studio-2008 mfc serial-port serial-communication