gpt4 book ai didi

c# - 如何识别USB插槽中插入的是什么设备?

转载 作者:可可西里 更新时间:2023-11-01 07:56:41 26 4
gpt4 key购买 nike

我想检测用户何时插入或移除 USB 声卡。当这种情况发生时,我已经设法真正捕捉到了事件,但我无法分辨插入的是什么。

我尝试了一种基于 this 的方法问题:

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)。

编辑:根据获奖提交者的建议,我创建了一个 full solution包含所有功能。

最佳答案

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

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

关于c# - 如何识别USB插槽中插入的是什么设备?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16620509/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com