Is there a way to attach an event handler to the list of running processes in C#?

c#, events, process, windows

Solution

You can also use WMI Events to track this.

Here is an example:

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) { }
}

There are a lot of process attributes that can be received. Like Priority, Description, Command Line arguments, etc. You can look in instanceDescription.Properties for details.

Problem

I'm currently writing a winforms application that is sensitive to programs being run in the background. At the moment I have a thread checking every second if the process I'm interested in has started/is still running, but I'm sure this would be much easier if I could just use an event to tell me when the user has opened/closed the application. Note that I am not starting the process manually within the program; the user has total control over that. Looking through the process documentation I don't see anything. Is there any way to hook into this?

Original source

Related problems