我一直在尝试监控何时插入或移除 USB 设备,并且它似乎工作得很好。现在唯一困扰我的是每次插入或移除设备时都会触发多次事件。
我可以毫无问题地对事件进行分组,但我很好奇为什么它首先会发生。
这是我正在使用的查询
SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2 or EventType = 3
插入或移除设备时触发。以及以下修改版本...
SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2 or EventType = 3 GROUP WITHIN 1
以 1 秒的间隔对事件进行分组。有人可以解释为什么事件会被多次触发吗?
为了完整起见,这里是其余的代码。
static void Main(string[] args)
{
var watcher = new ManagementEventWatcher();
var query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2 or EventType = 3 GROUP WITHIN 1 ");
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Query = query;
watcher.Start();
Console.WriteLine("Press a key to exit.");
Console.ReadKey();
}
static void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
Console.WriteLine(string.Format("--> {0}", e.NewEvent.GetType().Name));
Console.WriteLine(string.Format(" {0}", e.NewEvent.ClassPath.ClassName));
Console.WriteLine(string.Format(" Properties [{0}]", e.NewEvent.Properties.Count));
foreach (var prop in e.NewEvent.Properties)
{
Console.WriteLine(string.Format(" Name: {0} Origin: {1} Type: {2} = {3}", prop.Name, prop.Origin, prop.Type.ToString(),prop.Value==null?"{null}":prop.Value.ToString()));
}
}