Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# USB设备已连接_C#_C# 4.0_Usb - Fatal编程技术网

C# USB设备已连接

C# USB设备已连接,c#,c#-4.0,usb,C#,C# 4.0,Usb,我正在尝试创建一个函数,在给定设备pid和vid的情况下检测usb设备是否已连接。我希望它看起来像这样,我只是不知道如何在C#中做到这一点 可能是 //import the System.Management namespace at the top in your "using" statement. Then in a method, or on a button click: ManagementObjectCollection collection; using (Management

我正在尝试创建一个函数,在给定设备pid和vid的情况下检测usb设备是否已连接。我希望它看起来像这样,我只是不知道如何在C#中做到这一点

可能是

//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

请编辑您的问题;添加以下几点可能会得到更好的答案:1。到目前为止你试过什么?2.你得到了什么结果?3.这与您期望的结果有何不同?我没有序列号,只有嵌套在usb中某处的供应商id和产品id。另外,WMI调用查找Win32_磁盘驱动器,而不是所有USB设备。您能帮我解决相关问题吗?
//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;
}
//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;
}