Home >Backend Development >C++ >How Can I Determine the Last Execution Time of a Stopped Process in .NET?

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

Barbara Streisand
Barbara StreisandOriginal
2025-01-21 00:41:09511browse

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:

<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>

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.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn