我刚将一些代码从xp移植到Windows 8.1。在xp上运行时,我的代码可以检测usb设备并确定com端口。看来这在Windows 8.1中已经发生了变化。
要获取xp中的com端口,我会使用以下方法:
private void SetComPort()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSSerial_PortName");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Detected PortName: {0}", queryObj["PortName"]);
Console.WriteLine("Driver Name: {0}", queryObj["InstanceName"]);
if (queryObj["InstanceName"].ToString().Contains(_driver))
{
_comPort = queryObj["PortName"].ToString();
}
if (queryObj["InstanceName"].ToString().Contains("USB") || queryObj["InstanceName"].ToString().Contains(_driver))
{
Console.WriteLine(queryObj["PortName"] + " is a USB to SERIAL adapter/converter");
}
}
}
在8.1 searcher.Get()
中运行此代码会返回0个对象。所以我搜索并找到以下代码,列出所有设备,但不是com端口:
private List<USBDeviceInfo> GetUSBDevices()
{
List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
var searcher = new ManagementObjectSearcher("root\\cimv2", @"Select * From Win32_USBHub");
foreach (var device in searcher.Get())
{
devices.Add(new USBDeviceInfo(
(String)device.GetPropertyValue("DeviceID"),
(String)device.GetPropertyValue("PNPDeviceID"),
(String)device.GetPropertyValue("Description"),
(String)device.GetPropertyValue("Name")
));
}
return devices;
}
如何通过DeviceID确定端口?