使用SetupDiGetClassDevs在Delphi中枚举串口

4
我正在尝试列举COM端口的“友好名称”。随着USB串行设备在运行时连接和断开,端口可能会动态更改。根据这个问题描述的可能方法,我尝试使用SetupDiGetClassDevs方法。我找到了这个示例代码,但它是为旧版本的setupapi单元编写的(当然,原始链接到homepages.borland.com不起作用)。我尝试使用当前JVCL的setupapi单元(JVCL340CompleteJCL221-Build3845),但它似乎与Delphi 7不兼容。我得到编译器错误:
if SetupDiGetDeviceRegistryProperty(DevInfoHandle,DeviceInfoData,
    RegProperty,
    @PropertyRegDataType,
    @S1[1],RequiredSize,@RequiredSize) then begin

在调用函数SetupDiGetDeviceRegistryProperty时,我收到了关于参数@PropertyRegDataType@RequiredSize的错误提示“实际参数和形式参数的类型必须相同”。
Delphi3000网站称该代码是2004年编写的,适用于Delphi 7,因此我不确定为什么它现在不能与Delphi 7一起使用,除非setupapi发生了变化。有没有人熟悉setupapi的更改可能导致这些问题?
我正在使用简单的控制台程序进行测试。使用语句为“windows,sysutils,classes,setupAPI,Registry;”
主要程序如下:
  begin
  ComPortStringList := SetupEnumAvailableComPorts;
  for Index := 0 to ComPortStringList.Count - 1 do
      writeln(ComPortStringList[Index]);
  end;
  end.

这个问题中的示例代码链接现在已经过时(2020年9月)。请查看Grzegorz Skoczylas的答案,该答案适用于Windows 10上的Delphi 7(并且适用于内置和USB串口适配器COM端口)。 - AlainD
6个回答

11

以下步骤在Windows 8.1上对我有效。使用TRegistry.Constructor中的参数KEY_READ很重要。

procedure  EnumComPorts(const   Ports:  TStringList);

var
  nInd:  Integer;

begin  { EnumComPorts }
  with  TRegistry.Create(KEY_READ)  do
    try
      RootKey := HKEY_LOCAL_MACHINE;
      if  OpenKey('hardware\devicemap\serialcomm', False)  then
        try
          Ports.BeginUpdate();
          try
            GetValueNames(Ports);
            for  nInd := Ports.Count - 1  downto  0  do
              Ports.Strings[nInd] := ReadString(Ports.Strings[nInd]);
            Ports.Sort()
          finally
            Ports.EndUpdate()
          end { try-finally }
        finally
          CloseKey()
        end { try-finally }
      else
        Ports.Clear()
    finally
      Free()
    end { try-finally }
end { EnumComPorts };

这个过程在Windows 10中应该也能正常工作,但我还没有检查过。 - Grzegorz Skoczylas
同样适用于Windows 7。 - Codebeat
1
虽然我还没有测试过这个,但我手动查看了Windows 10的Regedit,我在devicemap下没有看到serialcom键。 - Jerry Dodge
这个程序对我多年来都有效。它适用于Windows 7、8和10。目前我使用的是Windows 10专业版。你确定你在HKEY_LOCAL_MACHINE分支中检查过吗? - Grzegorz Skoczylas
这在Windows 10 20H2上无法工作。没有键HKEY_LOCAL_MACHINE\hardware\devicemap\serialcomm。 - Mehmet Fide
显示剩余2条评论

7
我通过以不同的标签提问,获得了一些更具体的建议。
原来,delphi3000.com的示例代码存在错误,JVCL代码也可能存在错误。在修复示例代码错误后,我使其正常工作。我还没有解决潜在的JVCL错误。
以下是枚举COM端口名称的工作代码(作为简单的控制台应用程序):
{$APPTYPE CONSOLE}
program EnumComPortsTest;


uses
  windows,
  sysutils,
  classes,
  setupAPI,
  Registry;

{$R *.RES}

var
   ComPortStringList : TStringList;

(*

The function below returns a list of available COM-ports
(not open by this or an other process), with friendly names. The list is formatted as follows:

COM1: = Communications Port (COM1)
COM5: = NI Serial Port (Com5)
COM6: = NI Serial Port (Com6)
COM7: = USB Serial Port (COM7)
COM8: = Bluetooth Communications Port (COM8)
COM9: = Bluetooth Communications Port (COM9)

This code originally posted at http://www.delphi3000.com/articles/article_4001.asp?SK=
errors have been fixed so it will work with Delphi 7 and SetupAPI from JVCL
*)

function SetupEnumAvailableComPorts:TstringList;
// Enumerates all serial communications ports that are available and ready to
// be used.

// For the setupapi unit see
// http://homepages.borland.com/jedi/cms/modules/apilib/visit.php?cid=4&lid=3

var
  RequiredSize:             Cardinal;
  GUIDSize:                 DWORD;
  Guid:                     TGUID;
  DevInfoHandle:            HDEVINFO;
  DeviceInfoData:           TSPDevInfoData;
  MemberIndex:              Cardinal;
  PropertyRegDataType:      DWord;
  RegProperty:              Cardinal;
  RegTyp:                   Cardinal;
  Key:                      Hkey;
  Info:                     TRegKeyInfo;
  S1,S2:                    string;
  hc:                       THandle;
begin
  Result:=Nil;
//If we cannot access the setupapi.dll then we return a nil pointer.
  if not LoadsetupAPI then exit;
  try
// get 'Ports' class guid from name

    GUIDSize := 1;    // missing from original code - need to tell function that the Guid structure contains a single GUID
    if SetupDiClassGuidsFromName('Ports',@Guid,GUIDSize,RequiredSize) then begin
//get object handle of 'Ports' class to interate all devices
       DevInfoHandle:=SetupDiGetClassDevs(@Guid,Nil,0,DIGCF_PRESENT);
       if Cardinal(DevInfoHandle)<>Invalid_Handle_Value then begin
         try
           MemberIndex:=0;
           result:=TStringList.Create;
//iterate device list
           repeat
             FillChar(DeviceInfoData,SizeOf(DeviceInfoData),0);
             DeviceInfoData.cbSize:=SizeOf(DeviceInfoData);
//get device info that corresponds to the next memberindex
             if Not SetupDiEnumDeviceInfo(DevInfoHandle,MemberIndex,DeviceInfoData) then
               break;
//query friendly device name LIKE 'BlueTooth Communication Port (COM8)' etc
             RegProperty:=SPDRP_FriendlyName;{SPDRP_Driver, SPDRP_SERVICE, SPDRP_ENUMERATOR_NAME,SPDRP_PHYSICAL_DEVICE_OBJECT_NAME,SPDRP_FRIENDLYNAME,}

             SetupDiGetDeviceRegistryProperty(DevInfoHandle,
                                                   DeviceInfoData,
                                                   RegProperty,
                                                   PropertyRegDataType,
                                                   NIL,0,RequiredSize);
             SetLength(S1,RequiredSize);

             if SetupDiGetDeviceRegistryProperty(DevInfoHandle,DeviceInfoData,
                                                 RegProperty,
                                                 PropertyRegDataType,
                                                 @S1[1],RequiredSize,RequiredSize) then begin
               KEY:=SetupDiOpenDevRegKey(DevInfoHandle,DeviceInfoData,DICS_FLAG_GLOBAL,0,DIREG_DEV,KEY_READ);
               if key<>INValid_Handle_Value then begin
                 FillChar(Info, SizeOf(Info), 0);
//query the real port name from the registry value 'PortName'
                 if RegQueryInfoKey(Key, nil, nil, nil, @Info.NumSubKeys,@Info.MaxSubKeyLen, nil, @Info.NumValues, @Info.MaxValueLen,
                                                        @Info.MaxDataLen, nil, @Info.FileTime) = ERROR_SUCCESS then begin
                   RequiredSize:= Info.MaxValueLen + 1;
                   SetLength(S2,RequiredSize);
                   if RegQueryValueEx(KEY,'PortName',Nil,@Regtyp,@s2[1],@RequiredSize)=Error_Success then begin
                     If (Pos('COM',S2)=1) then begin
//Test if the device can be used
                       hc:=CreateFile(pchar('\\.\'+S2+#0),
                                      GENERIC_READ or GENERIC_WRITE,
                                      0,
                                      nil,
                                      OPEN_EXISTING,
                                      FILE_ATTRIBUTE_NORMAL,
                                      0);
                       if hc<> INVALID_HANDLE_VALUE then begin
                         Result.Add(Strpas(PChar(S2))+': = '+StrPas(PChar(S1)));
                         CloseHandle(hc);
                       end;
                     end;
                   end;
                 end;
                 RegCloseKey(key);
               end;
             end;
             Inc(MemberIndex);
           until False;
//If we did not found any free com. port we return a NIL pointer.
           if Result.Count=0 then begin
             Result.Free;
             Result:=NIL;

           end
         finally
           SetupDiDestroyDeviceInfoList(DevInfoHandle);
         end;
       end;
    end;
  finally
    UnloadSetupApi;
  end;
end;



var
   index : integer;

begin

  ComPortStringList := SetupEnumAvailableComPorts;

  if (ComPortStringList <> nil) and (ComPortStringList.Count > 0) then
    for Index := 0 to ComPortStringList.Count - 1 do
      writeln(ComPortStringList[Index]);

end.

在这段代码中,SetupDiEnumDeviceInfo() 总是返回 false。 - Mehmet Fide

2

为了更轻松地操作,您可以考虑使用注册表,其中列出了这些名称,例如:

  ErrCode := RegOpenKeyEx(
    HKEY_LOCAL_MACHINE,
    'HARDWARE\DEVICEMAP\SERIALCOMM',
    0,
    KEY_READ,
    KeyHandle);

我省略了一些手势。

你还可以考虑使用WMI - 从Magenta Systems的这个示例中可以看到 - 现在你几乎可以获得所有与硬件相关的东西。


2

看起来在SetupApi.pas中,一些类型为PDWord的参数被替换成了var DWord。你只需要在代码中删除这些参数前面的'@'符号就可以了:

if SetupDiGetDeviceRegistryProperty(DevInfoHandle,DeviceInfoData,
                                    RegProperty,
                                    PropertyRegDataType,
                                    @S1[1],RequiredSize,RequiredSize) then begin

2
你是否开启了 "typed @ operator" 选项?在项目选项中,编译器选项卡下的 "语法选项" 中可以找到。如果启用该选项,很多第三方代码将无法运行。

此项目未选中“Typed @ operator”选项。我已在调用周围添加了{$VARSTRINGCHECKS OFF},解决了@S1[1]的错误。你还能想到其他可能的问题吗? - tim11g

0

我从 RRUZ 答案 中改编了下面的代码,用于串口类。在 Win10 20H2 下运行良好。

{$APPTYPE CONSOLE}

uses
  SysUtils,
  ActiveX,
  ComObj,
  Variants;


procedure  GetWin32_SerialPortInfo;
const
  WbemUser            ='';
  WbemPassword        ='';
  WbemComputer        ='localhost';
  wbemFlagForwardOnly = $00000020;
var
  FSWbemLocator : OLEVariant;
  FWMIService   : OLEVariant;
  FWbemObjectSet: OLEVariant;
  FWbemObject   : OLEVariant;
  oEnum         : IEnumvariant;
  iValue        : LongWord;
begin;
  FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
  FWMIService   := FSWbemLocator.ConnectServer(WbemComputer, 'root\CIMV2', WbemUser, WbemPassword);
  FWbemObjectSet:= FWMIService.ExecQuery('SELECT * FROM Win32_SerialPort','WQL',wbemFlagForwardOnly);
  oEnum         := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
  while oEnum.Next(1, FWbemObject, iValue) = 0 do
  begin
    // for other fields: https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-serialport
    Writeln(Format('DeviceID        %s',[String(FWbemObject.DeviceID)]));// String
    Writeln(Format('Name            %s',[String(FWbemObject.Name)]));// String
    Writeln(Format('Description     %s',[String(FWbemObject.Description)]));// String
    FWbemObject:=Unassigned;
  end;
end;


begin
 try
    CoInitialize(nil);
    try
      GetWin32_SerialPortInfo;
    finally
      CoUninitialize;
    end;
 except
    on E:EOleException do
        Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.

输出:

DeviceID        COM7
Name            Silicon Labs CP210x USB to UART Bridge (COM7)
Description     Silicon Labs CP210x USB to UART Bridge
Press Enter to exit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接