Главная страница | назад





Article #16474: Detecting COM ports

 Question and Answer Database

FAQ1474C.txt   Detecting COM ports
Category   :Windows API
Platform    :All
Product    :C++Builder  1.x

Question:

How do I have my software determine if a COM port is in use by
another windows application before I grab it for my own use? 
I need to create a DLL to check for an unused COM port and tell 
the user that it is available.

Answer:

The only way to detect if comm port is opened is to try to 
reopen it. Call OpenComm(lpCommName, wInQueue, wOutQueue). If it
fails, the comm is probably in use. If it succeeds, then you can
tell the user you've grabbed it .... and if the user doesn't want
it, you can CloseComm(Cid) it. In Win 3.1 if it returns value
from 0 to number_of_present_ports - 1, you know it is free for 
use. The negative value that OpenComm function returns means 
that some kind of error occured. To get the type of error call 
GetCommError function and read it. It is all well documented in
Win 3.1 API (SDK).(This is necessary because all of the comm
functions in the standard API require the ID of the communications
device, which you get through OpenComm ...)
In Windows 95, or NT comm ports are treated as files, and you
have to call CreateFile function with "COMx" parameter
(Windows 95), and "\.\\COMx" in NT. CreateFile function usualy
returns file handle or 0xFF....F as an invalid file handle. When 
you receive all of those f-s (they mean -1), call function
GetLastError, and receive error number. Number 5 means that the
file is already opened so you'll know what that means. Some
other application is holding a port you desperately wanted to 
open.

(This is necessary because all of the comm functions in the 
standard API require the ID of the communications device, which 
you get through OpenComm ...)

7/2/98 10:32:32 AM
 

Last Modified: 01-SEP-99