Home >Backend Development >C++ >How Can I Determine the Last Execution Time of a Stopped Process in .NET?
The .NET Process
class offers insights into currently active processes. However, it falls short when trying to determine the last execution time of a process that's already ended.
This challenge is effectively addressed using Windows Management Instrumentation (WMI). WMI allows monitoring process start and stop events. Here's a practical implementation:
<code class="language-csharp">using System; using System.Management; public class ProcessMonitor { public static void Main(string[] args) { // Watch for process starts using (var startWatch = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"))) { startWatch.EventArrived += StartWatch_EventArrived; startWatch.Start(); // Watch for process stops using (var stopWatch = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"))) { stopWatch.EventArrived += StopWatch_EventArrived; stopWatch.Start(); Console.WriteLine("Monitoring process activity. Press any key to exit."); Console.ReadKey(); } startWatch.Stop(); } } private static void StopWatch_EventArrived(object sender, EventArrivedEventArgs e) { Console.WriteLine($"Process stopped: {e.NewEvent.Properties["ProcessName"].Value}"); } private static void StartWatch_EventArrived(object sender, EventArrivedEventArgs e) { Console.WriteLine($"Process started: {e.NewEvent.Properties["ProcessName"].Value}"); } }</code>
To effectively monitor process events, this application requires elevated privileges. Adjust the application manifest accordingly.
Run the program. It will continuously monitor process starts and stops, displaying the process name each time. Press any key to end monitoring.
The above is the detailed content of How Can I Determine the Last Execution Time of a Stopped Process in .NET?. For more information, please follow other related articles on the PHP Chinese website!