Home >Backend Development >C++ >How Can I Track Process Start and Stop Events Using .NET and WMI?
.NET offers a powerful method for tracking process lifecycle events using Windows Management Instrumentation (WMI). This approach is particularly useful for determining the last execution time of a specific process.
By utilizing the Win32_ProcessTrace
classes, you can effectively monitor process starts and stops. The following code demonstrates how to achieve this:
<code class="language-csharp">using System; using System.Management; public class ProcessTracker { public static void Main() { // Initialize 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(); // Await user input to terminate the application. Console.WriteLine("Press any key to exit."); while (!Console.KeyAvailable) System.Threading.Thread.Sleep(50); // Stop event watchers upon application closure. startWatcher.Stop(); stopWatcher.Stop(); } private static void stopWatcher_EventArrived(object sender, EventArrivedEventArgs e) { // Process stop event handler; logs the process name. Console.WriteLine("Process stopped: {0}", e.NewEvent.Properties["ProcessName"].Value); } private static void startWatcher_EventArrived(object sender, EventArrivedEventArgs e) { // Process start event handler; logs the process name. Console.WriteLine("Process started: {0}", e.NewEvent.Properties["ProcessName"].Value); } }</code>
Remember: This application requires elevated privileges. Modify the application manifest accordingly. This code provides a robust solution for tracking process start and stop events, enabling precise identification of the last execution time for any given process.
The above is the detailed content of How Can I Track Process Start and Stop Events Using .NET and WMI?. For more information, please follow other related articles on the PHP Chinese website!