【问题标题】:USB Device Connected已连接 USB 设备
【发布时间】:2011-04-10 18:44:04
【问题描述】:

我正在尝试创建一个函数来检测是否在给定设备 pid 和 vid 的情况下连接了 USB 设备。我希望它看起来像这样,我只是不确定如何在 C# 中执行此操作。

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

【问题讨论】:

  • 请编辑您的问题;添加以下几点可能会为您提供更好的答案: 1.到目前为止您尝试了什么? 2. 你得到了什么结果? 3. 这与您预期的结果有何不同?

标签: c# c#-4.0 usb


【解决方案1】:

可能是这样的

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

【讨论】:

  • 我没有序列号,只有嵌套在 USB 中某处的供应商 ID 和产品 ID。此外,WMI 调用会查找 Win32_DiskDrives,而不是所有 USB 设备。
【解决方案2】:
//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;
}

【讨论】:

  • 你能帮我解决this相关的问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-06
  • 1970-01-01
相关资源
最近更新 更多