jester
jester

Reputation: 3489

WPF app, efficient way to show running processes

I am currently working on a WPF app that shows various statistics associated with a set of running processes. I use Process.GetProcesses() method to get the running processes and filter out a set of processes that I want to mmonitor based on certain criteria. Each process forms a tab in my WPF UI. Currently I have them in an ObservableCollection which is bound to the TabControl. Now processes matching my criteria may come up and exit anytime and I want the UI to refresh accordingly. Currently I am polling the current set of processes every few seconds to determine if anything new has come up or a running process has exited so that the UI reflects the changes accordingly, but this seems to be far from ideal. Is there a better way of doing it? What is the best approach to achieve this functionality?

Upvotes: 0

Views: 582

Answers (1)

StaWho
StaWho

Reputation: 2488

You can use ManagementEventWatcher Class:

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();
        }
    }
}

Upvotes: 1

Related Questions