13

How do I detect with C# on Windows the moment when an external application is being launched?

I tried the FilesystemWatcher which doesn't work because the file is not really changing. Also having a timer constantly check all the open processes might be a bit over kill. Is there any other way to do this? If not in C# is it possible to do so in C++ (if so please give me an example).

The reason I want to do this is for logging purposes.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
RC1140
  • 8,423
  • 14
  • 48
  • 71

1 Answers1

22

You can use System.Management and WMI (Windows Management Instrumentation)

class WMIEvent {
    public static void Main() {
        WMIEvent we = new WMIEvent();
        ManagementEventWatcher w= null;
        WqlEventQuery q;
        try {
            q = new WqlEventQuery();
            q.EventClassName = "Win32_ProcessStartTrace";
            w = new ManagementEventWatcher(q);
            w.EventArrived += new EventArrivedEventHandler(we.ProcessStartEventArrived);
            w.Start();
            Console.ReadLine(); // block main thread for test purposes
        }
        finally {
            w.Stop();
        }
 }

    public void ProcessStartEventArrived(object sender, EventArrivedEventArgs e) {    
        foreach(PropertyData pd in e.NewEvent.Properties) {
            Console.WriteLine("\n============================= =========");
            Console.WriteLine("{0},{1},{2}",pd.Name, pd.Type, pd.Value);
        }
  }
MarmouCorp
  • 1,573
  • 10
  • 9
  • @stalkerh How did you make this work? Various types, like the MangementEventWatcher, doesn't exist in System.Management or System.Mangement.Instrumentation. Where do I find them? Did I miss something? – Svish Mar 16 '09 at 14:01
  • Nevermind. Had to add a reference to System.Management dll as well. Not just add `using System.Management;`... *sigh* :p – Svish Mar 16 '09 at 14:03
  • Yeah i noticed that and fixed without posting here – RC1140 Mar 17 '09 at 06:45
  • I'm getting an error: "Unhandled Exception: System.Management.ManagementException: Access denied" – kirill2485 Dec 23 '16 at 04:20
  • 1
    You need to run it as administrator or else you get that Access denied exception. – FocusedWolf Jul 22 '17 at 18:15
  • It's probably worth mentioning that this is only .NET Framework 4.7.2 – Leo Gurdian Sep 19 '18 at 19:44