简体   繁体   English

如何从我的 Windows 服务中侦听进程启动事件?

[英]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.我希望我的 Windows 服务能够侦听特定进程(例如进程 A)何时运行并能够随意关闭它。 How possible is this?这有多大可能?

You can use the ManagementEventWatcher class to receive a notification when a process is started.您可以使用ManagementEventWatcher类在进程启动时接收通知。

Subscribes to temporary event notifications based on a specified event query.订阅基于指定事件查询的临时事件通知。

There is an example on the MSDN page which might fit your needs. MSDN 页面上有一个示例,可能适合您的需求。

The following example shows how the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent.下面的示例显示了在创建 Win32_Process 实例时客户端如何接收通知,因为事件类是 __InstanceCreationEvent。

The ManagementEventWatcher class allows you to set a WqlEventQuery to specify the type of WQL event to listen for. ManagementEventWatcher类允许您设置WqlEventQuery以指定要侦听的 WQL 事件的类型。 More information on WQL query options and structure are available in the WQL (SQL for WMI) docs and WMI Reference . WQL(WMI 的 SQL)文档WMI 参考中提供了有关 WQL 查询选项和结构的更多信息。

Alternatively, you can query an array of running processes returned by Process.GetProcesses() at an interval using a timer.或者,您可以使用计时器每隔一段时间查询Process.GetProcesses()返回的正在运行的进程数组。

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.然后,使用Process.GetProcessByName()或直接从Process.GetProcesses()返回的结果数组获取对进程的引用,并使用Process.Kill()方法终止进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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