Monitoring Process Execution History with .NET
Need to track when specific processes last ran on a system? While Process.GetProcessesByName
shows currently running processes, it doesn't offer historical data. This article demonstrates using Windows Management Instrumentation (WMI) to solve this.
Leveraging WMI for Process Monitoring
WMI provides access to process start and stop events via the Win32_ProcessTrace
classes. The following code snippet illustrates how to monitor these events:
<code class="language-csharp">using System; using System.Management; public class ProcessMonitor { public static void Main(string[] args) { // Create event watchers for process start and stop events ManagementEventWatcher startWatcher = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace")); startWatcher.EventArrived += StartWatcher_EventArrived; startWatcher.Start(); ManagementEventWatcher stopWatcher = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace")); stopWatcher.EventArrived += StopWatcher_EventArrived; stopWatcher.Start(); // Keep the console open until a key is pressed Console.WriteLine("Press any key to exit..."); Console.ReadKey(); // Stop event watchers startWatcher.Stop(); stopWatcher.Stop(); } private static void StopWatcher_EventArrived(object sender, EventArrivedEventArgs e) { Console.WriteLine($"Process stopped: {e.NewEvent.Properties["ProcessName"].Value}"); } private static void StartWatcher_EventArrived(object sender, EventArrivedEventArgs e) { Console.WriteLine($"Process started: {e.NewEvent.Properties["ProcessName"].Value}"); } }</code>
Important Considerations:
This code requires administrator privileges to function correctly. Remember to adjust the application manifest accordingly. Running multiple processes will allow you to observe the process start and stop events logged by the program.
The above is the detailed content of How Can I Retrieve the Execution History of Processes in .NET?. For more information, please follow other related articles on the PHP Chinese website!