ManagementEventWatcher and WqlEventQuery in c#

Yesterday, I was searching for some kind of snippet that will throw some notification when the system starts / stops some processes, thats when I came to know about the ManagementEventWatcher in c#.

ManagementEventWatcher allows us to subscribe for specific events and notifies us when those events occur.

For example, in the fore mentioned example, we need to create a ManagementEventWatcher for the events related to the spawning of processes. This is done using the WqlEventQuery class.

So first we start off writing the WqlEventQuery. This class helps us in constructing WMI event queries. For getting a notification when a process is started or stopped, we shall write a query as follows,

WqlEventQuery aProcessCreationQuery = new WqlEventQuery("SELECT * FROM
Win32_ProcessStartTrace");

or

WqlEventQuery aProcessCreationQuery = new WqlEventQuery("__InstanceCreationEvent",
new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\"");

The above query shall be used to subscribe for WMI events for Win32 process creation.

Now that we have created a query, we need to use the ManagementEventWatcher to assign this query so that we can start listening for the subscribed events. So we create an object of the ManagementEventWatcher for the query that we formed earlier.

ManagementEventWatcher aWatcher = new ManagementEventWatcher(aProcessCreationQuery);

After creating an object of the ManagementEventWatcher, we need to subscribe for the events that willbe raised by the watcher. So we go for,

aWatcher.EventArrived += new EventArrivedEventHandler(ProcessStarted);

Thats it. All we have to do now is just trigger the watcher. We do this by calling,

aWatcher.Start();

This is an asynchronous call and the reply comes thru’ the event, EventArrived. So whenever the OS spawns a process, the event will be raised.

WqlEventQuery might have solved the fore mentioned problem, but I really don’t know how effective it is. If I get to know about them more, I will post it in here.

Tags: , ,

One comment

Leave a comment