【问题标题】:How to monitor process/program execution in windows?如何在 Windows 中监视进程/程序执行?
【发布时间】:2009-02-04 07:15:16
【问题描述】:

我们正在尝试开发一个小型应用程序,它可以监控 Windows 机器中正在执行的程序/进程。

如果程序/进程不应该运行,它应该被阻止。它的工作原理类似于防病毒软件。

这是基本思想。

我想知道如何连接到操作系统以获取有关试图在机器中运行的每个程序/进程的通知。

【问题讨论】:

    标签: windows events process executable


    【解决方案1】:

    最简单的方法是使用 WMI。专门监视 Win32_ProcessStartTrace。这比 Win32_Process 更好,因为它设置为使用事件,而 Win32_Process 需要轮询,这更占用 CPU。下面是如何在 C# 中执行此操作。首先确保将 System.Management 设置为您的项目的参考。

        public System.Management.ManagementEventWatcher mgmtWtch;
    
        public Form1()
        {
            InitializeComponent();
            mgmtWtch = new System.Management.ManagementEventWatcher("Select * From Win32_ProcessStartTrace");
            mgmtWtch.EventArrived += new System.Management.EventArrivedEventHandler(mgmtWtch_EventArrived);
            mgmtWtch.Start();
        }
    
        void mgmtWtch_EventArrived(object sender, System.Management.EventArrivedEventArgs e)
        {
            MessageBox.Show((string)e.NewEvent["ProcessName"]);
        }
    
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            mgmtWtch.Stop();
        }
    

    每次启动新进程时,代码都会生成一个消息框。从那里您可以检查白名单/黑名单并采取适当的行动。

    【讨论】:

    • 不幸的是,WMI 似乎比创建进程晚了 5 秒才传递通知。对于实时通知或对短期任务做任何事情都没有用。
    • 我在微软的网站上找到了一个相同任务的示例here,但它有同样的问题。
    • Gah... 使用 WMI 比手动轮询进程列表更占用 CPU(它只发生在 WMI 服务进程而不是您的进程中)。此外,如果您的应用程序崩溃,订阅将继续在 WMI 服务中运行,占用 CPU...
    【解决方案2】:

    我还没有尝试获得实时通知。然而,这里是如何在 C# 中运行进程

    using System.Diagnostics;
    
     //Somewhere in your method
    
    Process[] runningList = Process.GetProcesses();
    
    foreach(Process p in runningList){
    Console.WriteLine("Process: {0} ID: {1}", p.ProcessName, p.Id);
    }
    

    您还可以使用进程的以下道具

    • StartTime - 显示进程开始的时间
    • TotalProcessorTime - 显示进程占用的 CPU 时间量
    • 线程 - 允许访问进程中的线程集合

    【讨论】:

      【解决方案3】:

      我会使用常量 WH_GETMESSAGE 检查 Win32-api SetWindowsHookEx,以便在创建新窗口时向您的程序添加回调。

      http://pinvoke.net/default.aspx/user32.SetWindowsHookEx

      谷歌该 API 和 WH_GETMESSAGE 以了解更多信息。

      还可以查看以下文章/代码库: http://www.vbaccelerator.com/home/Vb/Code/Libraries/Hooks/vbAccelerator_Hook_Library/article.asp

      http://www.codeproject.com/KB/DLL/hooks.aspx?fid=2061&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=76&select=726975

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-14
        • 1970-01-01
        • 2023-03-28
        • 1970-01-01
        • 2012-10-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多