Ed.
Ed.

Reputation: 966

Can I check to see if a COM port can be opened without actually opening it?

Typically, on a PC, there is some non-standard set of COM ports available for use by a terminal emulator. I would like to be able to scan ports COM1-COM32 to see which (if any) of those ports can be opened as a serial port. I can do this be simply calling CreateFile() on all those ports; however, then I actually have to open/close (and affect DTR/RTS) the port momentarily.

I want to provide an accurate list to the user of the ports that are available. The problem is that I don't want to affect the DTR/RTS lines of the ports that are not currently being used because there may be hardware connected to those ports that does not want to see any transition on DTR/RTS.

Is there a way to just ask the question: "Will CreateFile() succeed?" on specified com ports?

Upvotes: 2

Views: 1278

Answers (3)

Serge Wautier
Serge Wautier

Reputation: 21878

HKLM/HARDWARE/DEVICEMAP/SERIALCOMM is my favorite.

this solution shows the best ease of implementation vs accuracy ratio IMO.

It's accurate enough in most cases although I've seen at least one manufacturer of USB to Serial ports whose HW doesn't always list in there (FTDI IIRC).

Upvotes: 0

Marko Teiste
Marko Teiste

Reputation: 362

Several ways

a) QueryDosDevice() - check against COM in the names

b) GetDefaultCommConfig() - Go thru all the possible serial names, eg. try to get config for COM1, COM2, ... COMn

c) HKLM/HARDWARE/DEVICEMAP/SERIALCOMM - Enumerate the keys

d) SetupAPI - if I would remember how to use this without extensively consulting the reference manual I would not be human

e) ???

Edited: as noted by Peter, beyond enumeration, there is no function that can tell you if you can access the device or not.

Upvotes: 0

Peter Ruderman
Peter Ruderman

Reputation: 12485

No, there is no way to ask such a question. The answer wouldn't be meaningful anyway. Even if the OS determined that opening a COM port will succeed at some point in time, that doesn't mean you can open it later. (It might get opened by another application, for instance.) You can use the SetupDiXXX functions to enumerate the COM ports in the system, but this really just returns information about the installed and active drivers. It doesn't provide any guarantees beyond that.

Upvotes: 2

Related Questions