这些信息也可以通过
SetupAPI正式获取。使用
dbcc_name
传递给
SetupDiOpenDeviceInterface
,并使用
SPDRP_FRIENDLYNAME
传递
SetupDiGetDeviceRegistryProperty
以获取友好名称。
以下是一些Delphi代码,可用于执行此操作。(抱歉,您需要独立将其翻译为C#)。
function ConvertDbccNameToFriendlyName(aDeviceInterfaceDbccName : string) : string;
var
deviceInfoHandle : HDEVINFO;
deviceInfoData : SP_DEVINFO_DATA;
deviceInterfaceData : SP_DEVICE_INTERFACE_DATA;
deviceInstanceId : string;
memberIndex : Cardinal;
begin
result := '';
deviceInfoHandle := SetupDiCreateDeviceInfoList(nil, 0);
if deviceInfoHandle <> INVALID_HANDLE_VALUE then
begin
try
FillChar(deviceInterfaceData, SizeOf(deviceInterfaceData), 0);
deviceInterfaceData.cbSize := SizeOf(deviceInterfaceData);
if SetupDiOpenDeviceInterface(deviceInfoHandle, PChar(aDeviceInterfaceDbccName), 0, @deviceInterfaceData) then
begin
try
memberIndex := 0;
while true do
begin
FillChar(deviceInfoData, SizeOf(deviceInfoData), 0);
deviceInfoData.cbSize := SizeOf(deviceInfoData);
if not SetupDiEnumDeviceInfo(deviceInfoHandle, memberIndex, deviceInfoData) then
begin
break;
end
else
begin
Inc(memberIndex);
end;
if TryGetDeviceFriendlyName(deviceInfoHandle, deviceInfoData, friendlyName) then
begin
result := friendlyName;
break;
end;
end;
finally
SetupDiDeleteDeviceInterfaceData(deviceInfoHandle, deviceInterfaceData);
end;
end;
finally
SetupDiDestroyDeviceInfoList(deviceInfoHandle);
end;
end;
end;
function TryGetDeviceFriendlyName(
var aDeviceInfoHandle : HDEVINFO;
var aDeviceInfoData : SP_DEVINFO_DATA;
out aFriendlyName : string) : boolean;
var
valueBuffer : array of byte;
regProperty : Cardinal;
propertyRegDataType : DWord;
friendlyNameByteSize : Cardinal;
success : boolean;
begin
aFriendlyName := '';
result := false;
regProperty := SPDRP_FRIENDLYNAME;
friendlyNameByteSize := 0;
SetupDiGetDeviceRegistryProperty(
aDeviceInfoHandle,
aDeviceInfoData,
regProperty,
propertyRegDataType,
nil,
0,
friendlyNameByteSize);
SetLength(valueBuffer, friendlyNameByteSize + sizeof(char));
success := SetupDiGetDeviceRegistryProperty(
aDeviceInfoHandle,
aDeviceInfoData,
regProperty,
propertyRegDataType,
@valueBuffer[0],
friendlyNameByteSize,
friendlyNameByteSize);
if success then
begin
PChar(@valueBuffer[friendlyNameByteSize])^ := char(0);
aFriendlyName := StrPas(PChar(@valueBuffer[0]));
end;
result := success;
end;
最后……如果您需要一种唯一标识USB设备的方式(虽然这不是您要求的,但通常也需要),请查看SetupDiGetDeviceInstanceId
。
DEV_BROADCAST_DEVICEINTERFACE
,因为它是一个可变大小的结构体(以ANYSIZE数组结束)。框架将获得指向一块内存的指针,其大小由第一个结构成员确定。除非有一种方法告诉marshaler这一点,否则我认为您必须使用本地代码来完成此操作(这就是我所做的)。 - Scott Smith