zoukankan      html  css  js  c++  java
  • 使用WMI监控进程启动与结束

    需要添加引用System.Management

    代码:

    static void Main(string[] args)
    {
    //创建WQL事件查询,监视进程开启
    var qCreate = new WqlEventQuery("__InstanceCreationEvent", TimeSpan.FromSeconds(1), "TargetInstance ISA 'Win32_Process'");
    //创建WQL事件查询,监视进程关闭
    var qDelete = new WqlEventQuery("__InstanceDeletionEvent", TimeSpan.FromSeconds(1), "TargetInstance ISA 'Win32_Process'");

    //创建事件查询的侦听器(ManagementEventWatcher)
    var wCreate = new ManagementEventWatcher(qCreate);
    var wDelete = new ManagementEventWatcher(qDelete);

    //事件注册
    wCreate.EventArrived += (sender, e) =>
    {
    Console.WriteLine("开启进程:{0}", GetInfo(e.NewEvent));
    };
    wDelete.EventArrived += (sender, e) =>
    {
    Console.WriteLine("关闭:{0}", GetInfo(e.NewEvent));
    };

    //开始异步侦听
    wCreate.Start();
    wDelete.Start();

    Console.WriteLine("按任意键结束");
    Console.ReadKey();//*/
    }

    //输出事件对应的ManagementBaseObject(本例中的Win32_Process实例)的信息

    static string GetInfo(ManagementBaseObject mobj)

    {
    var instance = (ManagementBaseObject)mobj["TargetInstance"];
    return string.Format("{0} - {1} - {2}", instance["Name"],instance["ProcessId"], DateTime.Now);
    }

    运行结果:

  • 相关阅读:
    Swift
    Swift
    第二章_session管理
    HDU-1387-Team Queue
    Install Orace 11g on Solaris 10 Sparc 64 bit
    Linux 多学习过程
    dispatch_once认识分析
    关于包围神经猫的想法实现
    嵌入在网站上Flash播放机(2)
    初学者应学会如何加快seo
  • 原文地址:https://www.cnblogs.com/moonlight-zjb/p/3641881.html
Copyright © 2011-2022 走看看