Sometimes you might want to listen for a Process Start and do some Actions.
To start listening, just run the following code:
public void StartProcessMonitoring() { // Create event query to be notified within 1 second of a change in a service WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\""); // Create the Watcher watcher = new ManagementEventWatcher(); watcher.Query = query; watcher.EventArrived += new EventArrivedEventHandler(ProcessStartEvent); watcher.Start(); }
The callback could then look like this:
public static void ProcessStartEvent(object sender, EventArrivedEventArgs e) { ManagementBaseObject targetInstance = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value; string processName = targetInstance.Properties["Name"].Value.ToString(); if (processName == "myprocess.exe") { // Do whatever you want } }
I created a member for the watcher Object
ManagementEventWatcher watcher;
and closed it when the App closes, otherwise I got a COM Error or something.
Here’s the cleanup Code:
watcher.Stop(); watcher.Dispose();