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

I am currently writing a winforms application that is sensitive to programs running in the background. At the moment I have a thread checking every second if the process that interests me is running / still running, but I'm sure it would be a lot easier if I could just use the event to tell me when the user opened / closed the application. Please note that I do not start the process manually within the program; The user has full control over this. Looking through the process documentation, I see nothing. Is there any way to connect to this?

+6
source share
2 answers

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 many process attributes that can be obtained. Like arguments Priority, Description, Command Line, etc. You can look at instanceDescription.Properties for more information.

+4
source

Well, at least it should be possible to create a binding to the CreateProcess WinAPI method. You can even use this to prevent the process from starting at all (simply returning false if you do not want the process to start). Of course, you will have to make a hook on every method that can start a new process, but there is not much.

As suggested by Purrformance, http://easyhook.codeplex.com/ is a great library that makes it easy to create hooks from .NET.

+2
source

All Articles