简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM