如何识别插入USB插槽的设备

本文关键字:插槽 USB 插入 何识别 识别 | 更新日期: 2023-09-27 18:14:06

我想检测用户何时插入或移除USB声卡。当这种情况发生时,我已经成功地捕捉到了这个事件,但我不知道刚刚插入了什么。

我尝试了一个基于这个问题的方法:

string query =
    "SELECT * FROM __InstanceCreationEvent " +
    "WITHIN 2 "
  + "WHERE TargetInstance ISA 'Win32_PnPEntity'";
var watcher = new ManagementEventWatcher(query);
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Start();

当我通过EventArrived事件获得通知时,我不知道如何确定刚刚插入的设备的实际名称。我已经把所有的属性都看了一遍,但还是没有一点头绪。

我还尝试了一个不同的查询:

var query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent where EventType = 1 or EventType = 2");
var watcher = new ManagementEventWatcher(query);
watcher.EventArrived += watcher_EventArrived;
watcher.Stopped += watcher_Stopped;
watcher.Query = query;
watcher.Start();

但也无济于事。有没有办法找到被插入或移除的设备的名称?

底线是我想知道USB声卡何时插入或从系统中取出。它应该可以在Windows 7和Vista上工作(尽管我将只满足于Win7)。

编辑:根据获奖提交者的建议,我创建了一个完整的解决方案,包含了所有的功能。

如何识别插入USB插槽的设备

如果我使用第一个代码,我可以这样定义我的事件:

    // define USB class guid (from devguid.h)
    static readonly Guid GUID_DEVCLASS_USB = new Guid("{36fc9e60-c465-11cf-8056-444553540000}");
    static void watcher_EventArrived(object sender, EventArrivedEventArgs e)
    {
        ManagementBaseObject instance = (ManagementBaseObject )e.NewEvent["TargetInstance"];
        if (new Guid((string)instance["ClassGuid"]) == GUID_DEVCLASS_USB)
        {
            // we're only interested by USB devices, dump all props
            foreach (var property in instance.Properties)
            {
                Console.WriteLine(property.Name + " = " + property.Value);
            }
        }
    }

它会输出如下内容:

Availability =
Caption = USB Mass Storage Device
ClassGuid = {36fc9e60-c465-11cf-8056-444553540000}
CompatibleID = System.String[]
ConfigManagerErrorCode = 0
ConfigManagerUserConfig = False
CreationClassName = Win32_PnPEntity
Description = USB Mass Storage Device
DeviceID = USB'VID_18A5&PID_0243'07072BE66DD78609
ErrorCleared =
ErrorDescription =
HardwareID = System.String[]
InstallDate =
LastErrorCode =
Manufacturer = Compatible USB storage device
Name = USB Mass Storage Device
PNPDeviceID = USB'VID_18A5&PID_0243'07072BE66DD78609
PowerManagementCapabilities =
PowerManagementSupported =
Service = USBSTOR
Status = OK
StatusInfo =
SystemCreationClassName = Win32_ComputerSystem
SystemName = KILROY_WAS_HERE

这应该包含您需要的所有内容,包括您可以通过instance["DeviceID"]之类的东西获得的设备ID。

EDIT 1:哦,这不是一个USB存储设备,只是一个USB设备。我将寻找另一个解决方案。


描述同一问题的两个链接:

http://hintdesk.com/c-catch-usb-plug-and-unplug-event/

http://social.msdn.microsoft.com/forums/en us/wpf/thread/37123526 - 83 - fa - 4 - e96 a767 - 715 fe225bf28/

if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent")
{
    Console.WriteLine("USB was plugged in");
    //Get disk letter
    foreach (ManagementObject partition in new ManagementObjectSearcher(
"ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + mbo.Properties["DeviceID"].Value
+ "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
    {
        foreach (ManagementObject disk in new ManagementObjectSearcher(
                    "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='"
                        + partition["DeviceID"]
                        + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
        {
            Console.WriteLine("Disk=" + disk["Name"]);
        }
    }
}

当我尝试@AngryHacker解决方案时,我注意到DeviceChangedEventArgs类没有被调用。我删除了它,只是在watcher_eventArrived方法中添加了Console.WriteLines()

除了删除DeviceChangedEventArgs之外,以下是我的更改:

 (at line 46 in EstablishedWatchEvents)
 // setup the query to monitor removal
const string qryRemoval = "SELECT *" +  "FROM __InstanceDeletionEvent "
             + "WITHIN 2 " + "WHERE TargetInstance ISA 'Win32_PnPEntity' ";
 #region Events
 private void insertWatcher_EventArrived(object sender, EventArrivedEventArgs e)
 {
     var mbo = (ManagementBaseObject) e.NewEvent["TargetInstance"];
     if (new Guid((string) mbo["ClassGuid"]) == GUID_DEVCLASS_USB)
     {
         var deviceName = (string) mbo["Name"];
         Console.WriteLine(deviceName + " was inserted");
     }
 }
 private void removeWatcher_EventArrived(object sender, EventArrivedEventArgs e)
 {
     var mbo = (ManagementBaseObject)e.NewEvent["TargetInstance"];
     if (new Guid((string)mbo["ClassGuid"]) == GUID_DEVCLASS_USB)
     {
         var deviceName = (string)mbo["Name"];
         Console.WriteLine(deviceName + " was removed");
     }
 }
 #endregion