tags:

views:

263

answers:

1

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.

+13  A: 

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
Thanks perfect reply works exactly how i wanted.
RC1140
@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
Nevermind. Had to add a reference to System.Management dll as well. Not just add `using System.Management;`... *sigh* :p
Svish
But the `w = new ProcessStartEventArrived(q);` still doesn't work...
Svish
My bad that's `w = new ManagementEventWatcher (q);` (edited)
MarmouCorp
Yeah i noticed that and fixed without posting here
RC1140