简体   繁体   English

如果启动了新进程(应用程序!),如何捕获事件?

[英]How to capture the event if a new process (application!) is started?

I would like to have some eventhandler which raise if a new application is started. 我想有一些事件处理程序,如果启动了新的应用程序,则会引发该事件处理程序。 I've heard that this is possible by using a hook but the only examples I can find are based on mouse/keyboard events. 我听说可以通过使用钩子来实现,但是我只能找到基于鼠标/键盘事件的示例。

What is an example link of how I can create such a hook in C#? 如何在C#中创建此类钩子的示例链接是什么?

Oh and btw: Nope, I don't want to use WMI which could be a solution as well but it's not an option in my case. 哦,顺便说一句:不,我不想使用WMI ,它也可以是一种解决方案,但在我看来,这不是一个选择。

You can use a far from elegant solution which is perform a polling to the processes in the system. 您可以使用一种绝妙的解决方案,即对系统中的进程进行轮询。

Process[] currentProcessList = Process.GetProcesses();

List<Process> newlyAddedProcesses = new List<Process>();
while (true)
{
    newlyAddedProcesses.Clear();
    Process[] newProcessList = Process.GetProcesses();

    foreach (Process p in newProcessList)
    {
        if (!currentProcessList.Contains(p))
        {
            newlyAddedProcesses.Add(p);
        }
    }

    //TODO: do your work with newlyAddedProcesses

    System.Threading.Thread.Sleep(500);
    currentProcessList = newProcessList;
}

If your application doesn't need a high accuracy you can setup a big sleep time between polls which would make it much less time consuming. 如果您的应用程序不需要很高的精度,则可以在两次轮询之间设置较大的睡眠时间,这样可以减少耗时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM