加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 注册流程开始时间的最佳方法是什么?

发布时间:2020-12-15 08:07:10 所属栏目:百科 来源:网络整理
导读:我正在编写一个程序,必须记录启动记事本等过程的时间. 我认为创建一个每秒检查所有进程的Timer是很好的.但我认为它会减慢用户的计算机速度.有更好的方法吗? 解决方法 最初为所有正在运行的进程确定创建时间.然后 使用WMI注册进程创建事件. 有关如何将WMI用
我正在编写一个程序,必须记录启动记事本等过程的时间.
我认为创建一个每秒检查所有进程的Timer是很好的.但我认为它会减慢用户的计算机速度.有更好的方法吗?

解决方法

最初为所有正在运行的进程确定创建时间.然后
使用WMI注册进程创建事件.

有关如何将WMI用于流程创建事件的小示例,请参阅下面的代码:

static void Main(string[] args)
{
  using (ManagementEventWatcher eventWatcher =
            new ManagementEventWatcher(@"SELECT * FROM 
   __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_Process'"))
  {
    // Subscribe for process creation notification.
    eventWatcher.EventArrived += ProcessStarted_EventArrived; 
    eventWatcher.Start();
    Console.In.ReadLine();
    eventWatcher.EventArrived -= ProcessStarted_EventArrived;
    eventWatcher.Stop();
  }
}


static void ProcessStarted_EventArrived(object sender,EventArrivedEventArgs e)
{
  ManagementBaSEObject obj = e.NewEvent["TargetInstance"] as ManagementBaSEObject;

  // The Win32_Process class also contains a CreationDate property.
  Console.Out.WriteLine("ProcessName: {0} " + obj.Properties["Name"].Value);
}

开始编辑:

我进一步研究了使用WMI进行流程创建检测,并且使用Win32_ProcessStartTrace类有一个(更多)资源友好解决方案(但需要管理权限)(有关详细信息,请参阅TECHNET):

using (ManagementEventWatcher eventWatcher =
          new ManagementEventWatcher(@"SELECT * FROM Win32_ProcessStartTrace"))
{
  // Subscribe for process creation notification.
  eventWatcher.EventArrived += ProcessStarted_EventArrived;
  eventWatcher.Start();
  Console.Out.WriteLine("started");
  Console.In.ReadLine();
  eventWatcher.EventArrived -= ProcessStarted_EventArrived;
  eventWatcher.Stop();
}

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

在此解决方案中,您不必设置轮询间隔.

结束编辑

开始编辑2:

您可以使用Win32_ProcessStopTrace类来监视进程停止事件.要结合进程启动和进程停止事件,请使用Win32_ProcessTrace类.在事件处理程序中使用ClassPath proberty来区分启动/停止事件:

using (ManagementEventWatcher eventWatcher =
       new ManagementEventWatcher(@"SELECT * FROM Win32_ProcessTrace"))
{          
  eventWatcher.EventArrived += Process_EventArrived;
  eventWatcher.Start();
  Console.Out.WriteLine("started");
  Console.In.ReadLine();
  eventWatcher.EventArrived -= Process_EventArrived;
  eventWatcher.Stop();
}

static void Process_EventArrived(object sender,EventArrivedEventArgs e)
{
  Console.Out.WriteLine(e.NewEvent.ClassPath); // Use class path to distinguish
                                               // between start/stop process events.
  Console.Out.WriteLine("ProcessName: {0} " 
      + e.NewEvent.Properties["ProcessName"].Value);     
}

结束编辑2

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读