Tag Archives: Win32_ProcessStartTrace
How to know if a process has stopped or started using events in C#
There are numerous of ways to detect if a new process has started or stopped, sadly the majority of them are extremely inefficient as it requires you to keep looping through the active process constantly to see if a new one appeared in the array or if one is not there any more.
Luckily the windows Win32_ProcessStartTrace
and Win32_ProcessStopTrace
classes are here to help out.
The first thing we need to do is reference System.Management.dll in our project. Then we need to define the scope in your class which we will be using.
1 | using System.Management; |
After that we need to initialise the class which will contain the process start and process stopped events and add the handlers and their methods.
Add the two following variables in your Class.
1 2 | ManagementEventWatcher processStartEvent = new ManagementEventWatcher("SELECT * FROM Win32_ProcessStartTrace"); ManagementEventWatcher processStopEvent = new ManagementEventWatcher("SELECT * FROM Win32_ProcessStopTrace"); |
In your constructor the event handlers need to be added.
1 2 | processStartEvent.EventArrived += new EventArrivedEventHandler(processStartEvent_EventArrived); processStopEvent.EventArrived += new EventArrivedEventHandler(processStopEvent_EventArrived); |
and then their event methods that will be trigged when a process either starts or stops.
1 2 3 4 5 6 7 8 9 | void processStartEvent_EventArrived(object sender, EventArrivedEventArgs e) { // A new process has started } void processStopEvent_EventArrived(object sender, EventArrivedEventArgs e) { // A process has been stopped } |
And finally we need to start the events by using
1 2 | processStartEvent.Start(); processStopEvent.Start(); |
Posted in C#.
Tagged C#, csharp, process start event, process stop event, snippet, Win32_ProcessStartTrace, Win32_ProcessStopTrace, winforms