一尘不染

.NET进程监视器

c#

有没有一种方法可以确定特定计算机上次运行进程的时间?

我可以使用以下命令来确定某个进程是否正在运行,但是如果此进程已停止,则该应用程序无法捕获该进程。

Process[] process = Process.GetProcessesByName(processName, serverName);

阅读 309

收藏
2020-05-19

共1个答案

一尘不染

WMI提供了一种跟踪以Win32_ProcessTrace类开始和终止的进程的方法。最好的例子展示。启动一个新的控制台应用程序,在Project + Add
Reference中,选择System.Management。粘贴以下代码:

using System;
using System.Management;

class Process {
  public static void Main() {
    ManagementEventWatcher startWatch = new ManagementEventWatcher(
      new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
    startWatch.EventArrived += new EventArrivedEventHandler(startWatch_EventArrived);
    startWatch.Start();
    ManagementEventWatcher stopWatch = new ManagementEventWatcher(
      new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"));
    stopWatch.EventArrived += new EventArrivedEventHandler(stopWatch_EventArrived);
    stopWatch.Start();
    Console.WriteLine("Press any key to exit");
    while (!Console.KeyAvailable) System.Threading.Thread.Sleep(50);
    startWatch.Stop();
    stopWatch.Stop();
  }

  static void stopWatch_EventArrived(object sender, EventArrivedEventArgs e) {
    Console.WriteLine("Process stopped: {0}", e.NewEvent.Properties["ProcessName"].Value);
  }

  static void startWatch_EventArrived(object sender, EventArrivedEventArgs e) {
    Console.WriteLine("Process started: {0}", e.NewEvent.Properties["ProcessName"].Value);
  }
}

编辑清单,使该程序提升运行。然后只需启动一些程序即可查看其工作情况。注意它不是特别快。

2020-05-19