我目前正在编写一个对后台运行的程序敏感的
winforms应用程序.目前我有一个线程检查每一秒如果我感兴趣的进程已经开始/仍在运行,但我确信如果我可以使用一个事件来告诉我用户何时打开会更容易/关闭了申请.请注意,我没有在程序中手动启动该过程;用户可以完全控制它.查看流程文档,我什么都看不到.有没有办法勾住这个?
解决方法
您还可以使用
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以获取详细信息.