我正在尝试从我们的 WPF 应用程序中的 usb com 端口获取总线报告的设备描述。找到了一个 powershell 脚本,它给出了准确的答案,但由于并非每个用户都有运行 powershell 的权限,所以很遗憾,使用 PowerShell.Create() 不是一个选项。
(Get-WMIObject Win32_PnPEntity | where {$_.name -match "\(com*"}).GetDeviceProperties("DEVPKEY_Device_BusReportedDeviceDesc").DeviceProperties.Data
我尝试了以下组合,但我在 InvokeMethod 上得到“无法将‘System.String’类型的对象转换为类型‘System.Array’”或“无效的方法参数”。
using System;
using System.Management;
ManagementClass oClass = new ManagementClass("Win32_PnPEntity");
Object[] single = { "DEVPKEY_Device_BusReportedDeviceDesc" };
Array arr = (Array)new string[] { "DEVPKEY_Device_BusReportedDeviceDesc" };
Object[] singleArr = { single };
Object[] objsArr = { arr };
ManagementBaseObject inParams = oClass.GetMethodParameters("GetDeviceProperties");
inParams["devicePropertyKeys"] = single;
//inParams["devicePropertyKeys"] = arr;
//inParams["devicePropertyKeys"] = singleArr;
//inParams["devicePropertyKeys"] = objsArr;
oClass.InvokeMethod("GetDeviceProperties", single);
//oClass.InvokeMethod("GetDeviceProperties", singleArr);
//oClass.InvokeMethod("GetDeviceProperties", objsArr);
//oClass.InvokeMethod("GetDeviceProperties", inParams, null);
一切都发生在本地机器上。
还从 vromanov How to get Bus Reported Device Description using C# 找到了答案它有效,但似乎是一个矫枉过正的解决方案
最佳答案
GetDeviceProperties方法记录如下:
Uint32 GetDeviceProperties(
[in, optional] string devicePropertyKeys[],
[out] Win32_PnPDeviceProperty deviceProperties[]
);
下面是一个用 C# 调用它的示例代码:
foreach (var mo in new ManagementObjectSearcher(null, "SELECT * FROM Win32_PnPEntity").Get().OfType<ManagementObject>())
{
// get the name so we can do some tests on the name in this case
var name = mo["Name"] as string;
// add your custom test here
if (name == null || name.IndexOf("(co", StringComparison.OrdinalIgnoreCase) < 0)
continue;
// call Win32_PnPEntity's 'GetDeviceProperties' method
// prepare two arguments:
// 1st one is an array of string (or null)
// 2nd one will be filled on return (it's an array of ManagementBaseObject)
var args = new object[] { new string[] { "DEVPKEY_Device_BusReportedDeviceDesc" }, null };
mo.InvokeMethod("GetDeviceProperties", args);
// one mbo for each device property key
var mbos = (ManagementBaseObject[])args[1];
if (mbos.Length > 0)
{
// get value of property named "Data"
// not all objects have that so we enum all props here
var data = mbos[0].Properties.OfType<PropertyData>().FirstOrDefault(p => p.Name == "Data");
if (data != null)
{
Console.WriteLine(data.Value);
}
}
}
关于c# - 从 C# 中的 Win32_PnPEntity 获取 DEVPKEY_Device_BusReportedDeviceDesc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69362886/