0

我目前正在开发一个 WPF 应用程序,该应用程序显示与一组正在运行的进程相关的各种统计信息。我使用Process.GetProcesses()方法来获取正在运行的进程,并根据某些标准过滤掉一组我想要监控的进程。每个进程在我的 WPF UI 中形成一个选项卡。目前我把它们放在一个ObservableCollection绑定到 TabControl. 现在,符合我的条件的进程可能会随时出现并退出,我希望 UI 相应地刷新。目前,我每隔几秒钟轮询一次当前进程集,以确定是否有任何新的出现或正在运行的进程已退出,以便 UI 相应地反映更改,但这似乎远非理想。有更好的方法吗?实现此功能的最佳方法是什么?

4

1 回答 1

1

您可以使用ManagementEventWatcher 类

using System;
using System.Management;

namespace ProcessListener
{
    class Program
    {
        static void Main(string[] args)
        {
            ManagementEventWatcher psStartEvt = new ManagementEventWatcher("SELECT * FROM Win32_ProcessStartTrace");
            ManagementEventWatcher psStopEvt = new ManagementEventWatcher("SELECT * FROM Win32_ProcessStopTrace");

            psStartEvt.EventArrived += (s, e) =>
                {
                    string name = e.NewEvent.Properties["ProcessName"].Value.ToString();
                    string id = e.NewEvent.Properties["ProcessID"].Value.ToString();
                    Console.WriteLine("Started: {0} ({1})", name, id);
                };

            psStopEvt.EventArrived += (s, e) =>
                {
                    string name = e.NewEvent.Properties["ProcessName"].Value.ToString();
                    string id = e.NewEvent.Properties["ProcessID"].Value.ToString();
                    Console.WriteLine("Stopped: {0} ({1})", name, id);
                };

            psStartEvt.Start();
            psStopEvt.Start();
            Console.ReadLine();
        }
    }
}
于 2013-10-18T09:08:31.093 回答