我目前正在编写一个Winforms应用程序,它对后台运行的程序很敏感。 目前,我有一个线程检查每一秒,如果我感兴趣的进程已经开始/仍在运行,但我敢肯定,这将是更容易,如果我可以使用一个事件告诉我,当用户已经打开/closures了应用程序。 请注意,我不是在程序中手动启动该过程; 用户有完全的控制权。 通过过程文档看,我什么也没有看到。 有没有什么办法可以挂钩?
您也可以使用WMI事件来跟踪这个。
这里是一个例子:
static void Main(string[] args) { var query = new EventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance isa \"Win32_Process\""); using (var eventWatcher = new ManagementEventWatcher(query)) { eventWatcher.EventArrived += eventWatcher_EventArrived; eventWatcher.Start(); Console.WriteLine("Started"); Console.ReadLine(); eventWatcher.EventArrived -= eventWatcher_EventArrived; eventWatcher.Stop(); } } static void eventWatcher_EventArrived(object sender, EventArrivedEventArgs e) { try { var instanceDescription = e.NewEvent.GetPropertyValue("TargetInstance") as ManagementBaseObject; if(instanceDescription!=null) { var executablePath = instanceDescription.GetPropertyValue("ExecutablePath"); if(executablePath!=null) { Console.WriteLine("Application {0} started", executablePath.ToString()); } } } catch (ManagementException) { } }
有很多可以接收的进程属性。 像优先级,描述,命令行参数等。您可以查看instanceDescription.Properties的细节。
那么,至少应该可以在CreateProcess
WinAPI方法上创建一个钩子。 你甚至可以使用它来阻止进程启动(如果你不想让进程启动,只需返回false
)。 当然,你必须勾画出每一个可以开始一个新流程的方法,但并不是那么多。
由于Purrformance建议, http ://easyhook.codeplex.com/是一个很好的lib,可以轻松地从.NET创建钩子。