2010-09-10 240 views
5

我試圖做一個功能,檢測是否USB設備連接給定的設備PID和VID。我希望它看起來像這樣,我只是不知道如何在C#中做到這一點。USB設備連接

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

請編輯您的問題;增加以下幾點可能會給你更好的答案:1.你到目前爲止嘗試過什麼? 2.你得到了什麼結果? 3.這與你所期望的結果有何不同? – Piskvor 2010-09-10 15:07:24

回答

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; 
} 
+0

你能幫我解決[this](http://stackoverflow.com/q/7314257/75500)相關的問題嗎? – Shimmy 2011-10-04 12:43:36

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

+0

我沒有序列號,只有在usb中嵌套的供應商ID和產品ID。此外,該WMI調用查找Win32_DiskDrives,而不是所有的USB設備。 – Robert 2010-09-10 17:03:41

相關問題