Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting the launch of a application

Tags:

c++

c#

windows

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.

like image 573
RC1140 Avatar asked Mar 16 '09 10:03

RC1140


1 Answers

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);
        }
  }
like image 181
MarmouCorp Avatar answered Sep 21 '22 15:09

MarmouCorp