问题
I have developed a simple serial port application that works fine with COM ports lower than 10 (COM9, COM8, ... COM1). But when my device is attached on a port higher than 10, such as COM11, it doesn't connect and I get an INVALID_HANDLE. My code is:
comport = CreateFileA(comPortName.toAscii(), GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if(comport == INVALID_HANDLE_VALUE)
{
//Write exception code here
connectionStatus = CONNECTION_STATUS_DISCONNECTED;
}
What's wrong with my code? Is there any solution?
回答1:
To reach the COM Ports >= 10 you can use the driver's symbolic link. For example, for COM10 it is \\\\.\\COM10
.
Just try:
comport = CreateFileA("\\\\.\\COM10", GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if(comport == INVALID_HANDLE_VALUE)
{
// Write exception code here
connectionStatus = CONNECTION_STATUS_DISCONNECTED;
}
Of course, this also works for COM ports < 10.
回答2:
You need to prepend "\\.\" to the COM port name, so it should be something like:
CreateFileA("\\\\.\\COM10", ... )
Source: HOWTO: Specify Serial Ports Larger than COM9
来源:https://stackoverflow.com/questions/13191777/invalid-handle-error-when-connecting-to-com-port-higher-than-10-on-windows-7