Best practice to check com port exists and is acti

Hi all,

Whats the best way to test if a USB port exists and is active before I start sending data to it. I'd like to trap this kind of error and advise the user to go and rescan/reset the port before continuing. Our application talks to an FTDI  chip for legacy USB communications.
In this way I can make a gracefull exit by closing the port etc otherwise the application is prone to locking up.
Also how do I use the GetComPortNames procedure?
Thanks - all help and suggestions appreciated
Roger B

To detect if a COM port is available you could

1) try to open it and catch the exception when this fails. The exception indicates the COM port is not availble
2) use GetCOMPortNames like for example:

 sl: TStringList;
  sl := TStringList.Create;

Closing a COM port is always done via vaComm.Close;

And how i can detect if was disconnected when app is running?

Also you can post a example managing this kind of exception for async32?

The OnError event should be triggered. The error codes that can be returned can be one of the following:

Bruno Fierens2017-12-26 10:49:13

I get a barrage of dialog boxes complaining if a VaComm1->WriteText(asSomeString); is sent after the serial (USB) is pulled during a serial session.

I have tried to trap the error message unsuccessfully with try / catch block on the VaComm1->WriteText line ....   However, I found a work around that works:

VaComm1->ReadBufUsed();     //... Did we LOSE the COM port (disconnected from Windows)
catch (...)
Memo1->Lines->Add("Failed sending message to COM port");

This solution, provided a means from having my clients bring up Windows Task Manager and killing my application.   Not sure why I couldn't "catch" the actual offending line, VaComm1->WriteText().

Hope this is helpful for others.

Thanks for sharing.

When working with USB devices, note that the only way Windows notifies applications of USB device removal is:  , at serial port API level, Windows does not signal this unfortunately.
1 Like

So the only way to detect if a USB cable disconnect cause the virtual COM port "vanish"
is to trap this WM_DEVICECHANGE message ?


That is correct.