How to listen for a process start event from my windows service?

Viewed 1197

I want my Windows service to be able to listen for when a particular process, process A, for example, runs and be able to shut it down at will. How possible is this?

1 Answers

You can use the ManagementEventWatcher class to receive a notification when a process is started.

Subscribes to temporary event notifications based on a specified event query.

There is an example on the MSDN page which might fit your needs.

The following example shows how the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent.

The ManagementEventWatcher class allows you to set a WqlEventQuery to specify the type of WQL event to listen for. More information on WQL query options and structure are available in the WQL (SQL for WMI) docs and WMI Reference.

Alternatively, you can query an array of running processes returned by Process.GetProcesses() at an interval using a timer.

Then, get a reference to the process using Process.GetProcessByName() or directly from the resulting array returned by Process.GetProcesses() and use the Process.Kill() method to kill the process.

Related