USB设备已连接

时间:2010-09-10 14:51:50

标签: c# c#-4.0 usb

我正在尝试使用设备pid和vid来检测是否连接了usb设备。我希望它看起来像这样,我只是不确定如何在C#中做到这一点。

public bool IsUsbDeviceConnected(string pid, string vid)
{
  //Code here
}

2 个答案:

答案 0 :(得分:5)

//using System.Management
public bool IsUsbDeviceConnected(string pid, string vid)
{   
  using (var searcher = 
    new ManagementObjectSearcher(@"Select * From Win32_USBControllerDevice"))
  {
    using (var collection = searcher.Get())
    {
      foreach (var device in collection)
      {
        var usbDevice = Convert.ToString(device);

        if (usbDevice.Contains(pid) && usbDevice.Contains(vid))
          return true;
      }
    }
  }
  return false;
}

答案 1 :(得分:3)

可能类似

//import the System.Management namespace at the top in your "using" statement. Then in a method, or on a button click:

ManagementObjectCollection collection;
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'"))
  collection = searcher.Get();
foreach (ManagementObject currentObject in collection)
{
  ManagementObject theSerialNumberObjectQuery = new ManagementObject("Win32_PhysicalMedia.Tag='" + currentObject["DeviceID"] + "'");
  MessageBox.Show(theSerialNumberObjectQuery["SerialNumber"].ToString());
}
collection.Dispose();

使用WMI