.NET 提供了一種使用 Windows Management Instrumentation (WMI) 追蹤進程生命週期事件的強大方法。 這種方法對於確定特定進程的最後執行時間特別有用。
透過使用Win32_ProcessTrace
類,您可以有效地監控進程的啟動和停止。 以下程式碼示範如何實現此目的:
<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>
請記住:此應用程式需要提升權限。 相應地修改應用程式清單。此程式碼提供了一個強大的解決方案來追蹤進程啟動和停止事件,從而能夠精確識別任何給定進程的最後執行時間。
以上是如何使用 .NET 和 WMI 追蹤進程啟動和停止事件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!