35

Is there a way to determine when the last time a specific machine last ran a process?

I can use the following to determine if a process is running, but the application cannot grab the process if it has since stopped.

Process[] process = Process.GetProcessesByName(processName, serverName);
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
Nick Vaccaro
  • 5,428
  • 6
  • 38
  • 60

2 Answers2

76

WMI provides a way to track processes starting and terminating with the Win32_ProcessTrace classes. Best shown with an example. Start a new Console application, Project + Add Reference, select System.Management. Paste this code:

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);
  }
}

Edit the manifest so this program runs elevated. Then simply start some programs to see it at work. Beware that it is not especially quick.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 2
    It works perfectly, but the delay is annoying, is there anyway to get it faster? – Murhaf Sousli May 13 '12 at 11:20
  • 1
    I just tried it and have a delay of less then 1 second. I think this is ok. – webber2k6 Nov 16 '12 at 07:29
  • 3
    It's great, I want to wait until a command-line application process was initialized but I'm relutanct to request to the user to the application to run as adm – Jack Apr 08 '16 at 04:50
6

You won't be able to do this using the Process class. However, it should be possible to figure out when an application was last run by configuring audit process tracking in Windows. The following links might get you started:

Audit process tracking

How can I track what programs come and go on my machine?

The process tracking will create entries in the Windows event log which you can then access using C#.

Community
  • 1
  • 1
Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316