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:
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}");
}
}
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3