使用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);
}

运行结果:

使用WMI监控进程启动与结束

上一篇:Nikita and string [思维-暴力] ACM


下一篇:在美国,一名 Uber 司机能赚多少?