3

Possible Duplicate:
Track started applications in Windows

I' like to create a program or service in C# which monitors when a user launches a certain application like excel or access. With System.Diagnostics.Process I can get the running processes but I want to monitor the event when a user launches the application. We'd like to create some sort of usage history.

Community
  • 1
  • 1
hoetz
  • 2,368
  • 4
  • 26
  • 58

3 Answers3

4

You can do it using WMI:

private ManagementEventWatcher WatchForProcessStart(string processName)
{
    string queryString =
        "SELECT TargetInstance" +
        "  FROM __InstanceCreationEvent " +
        "WITHIN  10 " +
        " WHERE TargetInstance ISA 'Win32_Process' " +
        "   AND TargetInstance.Name = '" + processName + "'";

    // The dot in the scope means use the current machine
    string scope = @"\\.\root\CIMV2";

    // Create a watcher and listen for events
    ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString);
    watcher.EventArrived += ProcessStarted;
    watcher.Start();
    return watcher;
}

private void ProcessStarted(object sender, EventArrivedEventArgs e)
{
    ManagementBaseObject targetInstance = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value;
    string processName = targetInstance.Properties["Name"].Value.ToString();
    Console.WriteLine(String.Format("{0} process started", processName));
}

it watches for array of 10 latest processes and calls event when it changes

Pavel Krymets
  • 6,253
  • 1
  • 22
  • 35
4

I did a small example using WqlEventQuery object to check if there is a new instance of a process. Afterwards check for the name and do as you want. If you want to improve my query - feel free to have a look at the according syntax description.

private static void lookForExcel()
{
    WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\"");
    ManagementEventWatcher watcher = new ManagementEventWatcher(query);
    watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
    watcher.Start();
    Console.ReadLine();
    watcher.Stop();
}

static void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
    string instanceName = ((ManagementBaseObject)e.NewEvent["TargetInstance"])["Name"].ToString();
    if (instanceName.ToLower()=="excel.exe")
    {
        Debug.WriteLine("Excel has been started ...");    
    }            
}
Pilgerstorfer Franz
  • 8,303
  • 3
  • 41
  • 54
0

Easiest way is to periodically check what processes are running, and compare to the previous list.

However you can get a notification on a process start. Documentation here:

You could also turn on "detailed tracking" in the security event log, which will then show every process started and ended on the system. That might be too much though.

Ben
  • 34,935
  • 6
  • 74
  • 113