WMI USB Monitor Several Events Released

I am trying to control when USB devices are inserted or removed, and it seems to work very well. The only thing that bothers me now is that the event is fired several times every time I connect the device or delete it.

I can group events without problems, but I'm curious why this happens in the first place.

This is the query that I am using

SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2 or EventType = 3 

Which is triggered when a device is inserted or removed. And the next modified version ...

 SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2 or EventType = 3 GROUP WITHIN 1 

Groups events in a single interval. Can someone explain why events are fired several times?

For completeness, the rest of the code is here.

  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())); } } 
+6
source share

Source: https://habr.com/ru/post/949083/


All Articles