我正在开发一个使用ManagementEventWatcher
来监控USB
事件的应用程序。代码正常工作但在某些情况下程序丢失了一些USB events
。从USB列出所有事件的正确方法是什么?
我正在使用以下代码,我正在使用两个查询来监视附加和从USB分离。我需要监控许多USB端口。
USB监视器
ManagementEventWatcher watchUSBattach = new ManagementEventWatcher();
ManagementEventWatcher watchUSBDettach = new ManagementEventWatcher();
WqlEventQuery queryUsbAttach = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 ");
watchUSBattach.EventArrived += new EventArrivedEventHandler(watchUSBEventAdd);
watchUSBattach.Query = queryUsbAttach;
watchUSBattach.Start();
WqlEventQuery queryUsbDettach = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 3");
watchUSBDettach.EventArrived += new EventArrivedEventHandler(watchUSBEventDettach);
watchUSBDettach.Query = queryUsbDettach;
watchUSBDettach.Start();
答案 0 :(得分:0)
在监控USB设备插入或移除时,我遇到过类似的事情。示例代码如下。当WithinInterval
属性设置为1ms时,我不会错过事件,但我在WMIProviderHost和相关服务中遭受了不合理的CPU负载。如果我将它设置为更合理的值(如3秒),那么如果它们从同一设备一起发生得太快(例如,如果设备自行重置),我会错过删除/创建事件。也许您的查询默认WithinInterval
太长并导致事件被删除?
WqlEventQuery q;
var scope = new ManagementScope("root\\CIMV2")
{Options = {EnablePrivileges = true}};
q = new WqlEventQuery
{
EventClassName = "__InstanceCreationEvent",
WithinInterval = TimeSpan.FromMilliseconds(1),
Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'"
};
InsertWatcher = new ManagementEventWatcher(scope, q);
InsertWatcher.EventArrived += (sender, args) =>
{
var instance = (ManagementBaseObject) args.NewEvent["TargetInstance"];
RaiseInserted(new PlugEventArgs {DevicePath = (string) instance["__PATH"]});
};
InsertWatcher.Start();