Getting notified by a Windows process change in C# .NET
December 1, 2016 Leave a comment
In this post we saw an example of using the ManagementEventWatcher object and and EventQuery query. The SQL-like query was used to subscribe to a WMI – Windows Management Instrumentation – level event, namely a change in the status of a Windows service. I won’t repeat the explanation here again concerning the techniques used. So if this is new to you then consult that post, the code is very similar.
In this post we’ll see how to get notified by the creation of a new Windows process. This can be as simple as starting up Notepad. A Windows process is represented by the Win32_Process WMI class which will be used in the query. We’ll take a slightly different approach and use the WqlEventQuery object which derives from EventQuery.
Consider the following code:
private static void RunManagementEventWatcherForWindowsProcess() { WqlEventQuery processQuery = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 2), "targetinstance isa 'Win32_Process'"); ManagementEventWatcher processWatcher = new ManagementEventWatcher(processQuery); processWatcher.Options.Timeout = new TimeSpan(0, 1, 0); Console.WriteLine("Open an application to trigger the event watcher."); ManagementBaseObject nextEvent = processWatcher.WaitForNextEvent(); ManagementBaseObject targetInstance = ((ManagementBaseObject)nextEvent["targetinstance"]); PropertyDataCollection props = targetInstance.Properties; foreach (PropertyData prop in props) { Console.WriteLine("Property name: {0}, property value: {1}", prop.Name, prop.Value); } processWatcher.Stop(); }
In the Windows service example we used the following query:
SELECT * FROM __InstanceModificationEvent within 2 WHERE targetinstance isa ‘Win32_Service’
The WqlEventQuery constructor builds up a very similar statement. The TimeSpan refers to “within 2”, i.e. we want to be notified 2 seconds after the creation event. “targetinstance isa ‘Win32_Process'” corresponds to “WHERE targetinstance isa ‘Win32_Service'” of EventQuery.
Run this code and open an application. I got the following output for Notepad++:
…and this for IE:
You can view all posts related to Diagnostics here.