Question

I'm new to C# hooking and am looking for a little information on where to do my research. I figured there are some folks here who may have done this before that might have a good idea of where to start!

My overall goal is simple- to create a C# application, if possible, that can search the current running processes on a machine for one matching a certain name (we can assume for this situation that it is unique, only 1 process of that name) and "hook" into the process. The goal would be to watch for that process to get hung up. If it crashes, freezes, or generally has any bad health event that windows is capable of detecting, I'd like to be able to find out about it. Then, based on what it sees, it does other stuff.

I was able to do something similar in Python 2.7 using Pai Mei, but that project has been long abandoned and I've grown rather fond of C# in the recent years.

So: Does this sound like something that is possible in C#? If so, does anyone have a good suggestion on where I can find some information on it? And finally, does anyone have some example code laying around they might be willing to share on the topic? =D

Thank you!

Was it helpful?

Solution

ManagementEventWatcher might be helpful to starts with. However, the complexity would be on how do you write or tune your WMI queries.

I don't own the following code and is been nicked from somewhere.

using System;
using System.Management;

class Process {
  public static void Main() {
    ManagementEventWatcher startWatch = new ManagementEventWatcher(
      new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
    startWatch.EventArrived += new EventArrivedEventHandler(startWatch_EventArrived);
    startWatch.Start();
    ManagementEventWatcher stopWatch = new ManagementEventWatcher(
      new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"));
    stopWatch.EventArrived += new EventArrivedEventHandler(stopWatch_EventArrived);
    stopWatch.Start();
    Console.WriteLine("Press any key to exit");
    while (!Console.KeyAvailable) System.Threading.Thread.Sleep(50);
    startWatch.Stop();
    stopWatch.Stop();
  }

  static void stopWatch_EventArrived(object sender, EventArrivedEventArgs e) {
    Console.WriteLine("Process stopped: {0}", e.NewEvent.Properties["ProcessName"].Value);
  }

  static void startWatch_EventArrived(object sender, EventArrivedEventArgs e) {
    Console.WriteLine("Process started: {0}", e.NewEvent.Properties["ProcessName"].Value);
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top