"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to determine the last execution time of a stopped process in .NET?

How to determine the last execution time of a stopped process in .NET?

Posted on 2025-04-22
Browse:281

How Can I Determine the Last Execution Time of a Stopped Process in .NET?

Tracking Down the Last Run Time of a Terminated .NET Process

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.

WMI: The Solution

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}");
    }
}

Essential: Elevated Permissions

To effectively monitor process events, this application requires elevated privileges. Adjust the application manifest accordingly.

How to Use

Run the program. It will continuously monitor process starts and stops, displaying the process name each time. Press any key to end monitoring.

Latest tutorial More>

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