How to determine if a machine physically has a serial port?

我的未来我决定 提交于 2019-12-10 10:42:44

问题


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?


回答1:


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




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/5575372/how-to-determine-if-a-machine-physically-has-a-serial-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!