You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Delphi 12 FireMonkey框架中获取Windows已连接设备列表?

在Delphi 12 FireMonkey中获取Windows设备列表(类似设备管理器)

要在FireMonkey框架下获取Windows设备列表,核心是调用Windows原生的SetupAPI系列函数,这些API专门用于枚举和管理系统设备。以下是具体实现步骤:

1. 准备依赖单元与类型

在Delphi项目代码开头添加Windows设备管理相关的API单元:

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, FMX.Types,
  FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView,
  Winapi.SetupAPI, Winapi.DevPropDef, Winapi.DeviceApi;

2. 枚举设备的核心实现

下面的代码会枚举系统中所有已连接的设备,并获取设备名称、描述等关键信息:

procedure TForm1.GetSystemDeviceList;
var
  hDevInfo: HDEVINFO;
  DeviceInfoData: TSPDeviceInfoData;
  DeviceName: array[0..MAX_PATH] of Char;
  DeviceDesc: array[0..MAX_PATH] of Char;
  i: Integer;
begin
  // 获取所有已连接设备的信息集合句柄
  hDevInfo := SetupDiGetClassDevs(nil, nil, 0, DIGCF_ALLCLASSES or DIGCF_PRESENT);
  if hDevInfo = INVALID_HANDLE_VALUE then Exit;

  try
    DeviceInfoData.cbSize := SizeOf(TSPDeviceInfoData);
    i := 0;
    // 循环枚举每个设备
    while SetupDiEnumDeviceInfo(hDevInfo, i, DeviceInfoData) do
    begin
      // 读取设备友好名称
      SetupDiGetDeviceRegistryProperty(hDevInfo, @DeviceInfoData, SPDRP_FRIENDLYNAME,
        nil, PByte(@DeviceName), sizeof(DeviceName), nil);
      // 读取设备描述
      SetupDiGetDeviceRegistryProperty(hDevInfo, @DeviceInfoData, SPDRP_DEVICEDESC,
        nil, PByte(@DeviceDesc), sizeof(DeviceDesc), nil);

      // 将信息添加到FireMonkey列表控件(示例用TListView)
      if DeviceName[0] <> #0 then
        ListView1.Items.Add.Text := StrPas(DeviceName) + ' - ' + StrPas(DeviceDesc)
      else
        ListView1.Items.Add.Text := StrPas(DeviceDesc);

      Inc(i);
    end;
  finally
    // 释放设备信息集合句柄,避免内存泄漏
    SetupDiDestroyDeviceInfoList(hDevInfo);
  end;
end;

3. 关键注意事项

  • 权限要求:部分设备信息需要管理员权限才能读取,可在项目属性的Manifest中设置requestedExecutionLevel为requireAdministrator,确保程序以管理员身份运行。
  • UI线程优化:若设备数量较多,枚举过程可能耗时,建议将枚举逻辑放到后台线程执行,避免阻塞FireMonkey的UI线程。
  • 扩展属性获取:通过修改SPDRP_*系列常量,还可以获取设备硬件ID、制造商、驱动版本等更多信息,比如SPDRP_MFG对应制造商名称,SPDRP_HARDWAREID对应硬件ID。

内容的提问来源于stack exchange,提问作者Zakaria Mimeche

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 11:42:43