0

我正在开发一个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();
4

1 回答 1

1

在监控 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();
于 2017-01-19T02:17:11.473 回答