thehilmisu
thehilmisu

Reputation: 342

Invalid handle error when connecting to COM port higher than 10 on Windows 7

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?

Upvotes: 3

Views: 4560

Answers (2)

mvp
mvp

Reputation: 116337

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

Upvotes: 2

David J
David J

Reputation: 1564

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.

Upvotes: 7

Related Questions