Check is com port is open

I'm writing a program that needs to check is the user has the com port open. Is there any way to check if it is open and not disrupt the com port if it is?
greg_100Asked:
Who is Participating?
 
jkrConnect With a Mentor Commented:
Well, you could just use

    HANDLE hPort;

    hPort   =   CreateFile  (   "COM1",
                                GENERIC_READ | GENERIC_WRITE,
                                0,
                                0,
                                OPEN_EXISTING,
                                0,
                                0
                            );

    if  (   INVALID_HANDLE_VALUE ==  hPort)
        {

            if ( ERROR_ACCESS_DENIED == GetLastError ())
            {
                // port in use
            }
        }

0
 
jkrCommented:
Just call 'CreateFile()' on the COM port in question - if it is in use, you'll get ERROR_ACCESS_DENIED
0
 
greg_100Author Commented:
Do you have an example of how to do this?
0
 
greg_100Author Commented:
jkr,

That worked all I had to add was CloseHandle(hPort); to the end.
0
 
jkrCommented:
Ooops, sorry, should have mentioned that...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.