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

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


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.


Well, at the very least, it should be possible to create a hook on the CreateProcess WinAPI method. You could even use that to prevent the process from starting at all (by simply returning false if you don't want the process to start). Of course, you'll have to make a hook on every method that can start a new process, but there's not all that many.

As Purrformance suggested, http://easyhook.codeplex.com/ is a great lib to easily create hooks from .NET.