关于c#进程创建监控的文章大多都是“遍历一次进程用if去判断存在或否”这样的方法,我觉得体验不是很好。这几天写的一个软件正好需要实时监控进程创建的模块,在网上找到了很不错的方法,整理一下分享出来给大家。

private void Watcher_NewProcessCreated()
        {
            EventQuery query = new EventQuery();
            query.QueryString = "SELECT * FROM" +
                " __InstanceCreationEvent WITHIN 1 " +
                "WHERE TargetInstance isa 'Win32_Process'";

            ManagementEventWatcher watcher =
                new ManagementEventWatcher(query);

            watcher.EventArrived += NewProcess_Created;

            watcher.Start();
        }
        private void NewProcess_Created(object sender, EventArrivedEventArgs se)
        {
            ManagementBaseObject e = se.NewEvent;
            string Processname = ((ManagementBaseObject)e["TargetInstance"])["Name"].ToString();
            string ExecutablePath = ((ManagementBaseObject)e["TargetInstance"])["ExecutablePath"].ToString();

            Debug.WriteLine("进程创建:"+Processname+",进程文件路径:"+ExecutablePath);
        }

参考(抄袭⁄(⁄⁄•⁄ω⁄•⁄⁄)⁄):http://blog.chinaunix.net/uid-108863-id-112154.html,http://blog.csdn.net/breaksoftware/article/details/50543906

05-28 21:23