2

I could try to open it, but if it is use by another program I will get an error and I need to be able to distinguish that case from the case where the machine physically has no serial port.

Any idea?

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551

3 Answers3

8

Just for complement the Serg answer, the Win32_SerialPort class used in this article reports the physical com ports, if you wanna enumerate all the serial ports including the USB-Serial/COM ports, you must use the MSSerial_PortName class located in the root\wmi namespace.

uses
  SysUtils,
  ActiveX,
  ComObj,
  Variants;

// Serial Port Name

procedure  GetMSSerial_PortNameInfo;
const
  wbemFlagForwardOnly = $00000020;
var
  FSWbemLocator : OLEVariant;
  FWMIService   : OLEVariant;
  FWbemObjectSet: OLEVariant;
  FWbemObject   : OLEVariant;
  oEnum         : IEnumvariant;
  iValue        : LongWord;
begin;
  FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
  FWMIService   := FSWbemLocator.ConnectServer('localhost', 'root\WMI', '', '');
  FWbemObjectSet:= FWMIService.ExecQuery('SELECT * FROM MSSerial_PortName','WQL',wbemFlagForwardOnly);
  oEnum         := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
  while oEnum.Next(1, FWbemObject, iValue) = 0 do
  begin
    Writeln(Format('Active          %s',[FWbemObject.Active]));// Boolean
    Writeln(Format('InstanceName    %s',[FWbemObject.InstanceName]));// String
    Writeln(Format('PortName        %s',[FWbemObject.PortName]));// String

    Writeln('');
    FWbemObject:=Unassigned;
  end;
end;


begin
 try
    CoInitialize(nil);
    try
      GetMSSerial_PortNameInfo;
      Readln;
    finally
    CoUninitialize;
    end;
 except
    on E:Exception do
    begin
        Writeln(E.Classname, ':', E.Message);
        Readln;
    end;
  end;
end.

for additional info about the serial ports try the classes located in the same namespace

  • MSSerial_CommInfo
  • MSSerial_CommProperties
  • MSSerial_HardwareConfiguration
  • MSSerial_PerformanceInformation
RRUZ
  • 134,889
  • 20
  • 356
  • 483
3

You can use WMI. Have a look at my old post

kludg
  • 27,213
  • 5
  • 67
  • 118
2

You could also read from registry:
Enumerating a List of systems Com Ports in Delphi

Community
  • 1
  • 1
BennyBechDk
  • 934
  • 7
  • 13