流程监控

时间:2018-10-31 11:28:16

标签: c# process

我正在创建外壳程序[screenshot](替换桌面)。它应该显示每个快捷方式是否正在运行。为了做到这一点,程序正在运行的进程列表中寻找快捷方式:

// 'shortcutsList' is an array of shortcut objects
// each object contains the variables
// 'exec' - path to program
// 'args' - command line arguments
// GetArguments(Process process) returns command line arguments of process

while (true)
{ 
    bool[] shortcutsExecuted = new bool[shortcutsList.Length];
    foreach (Process process in Process.GetProcesses())
    {
        string path = process.MainModule.FileName;
        for (int i = 0; i < shortcutsList.Length; i++)
        {
            if ( (shortcutsList[i].exec == path) &&
                 ( (shortcutsList[i].args == "") || (GetArguments(process) == shortcutsList[i].args)))
            {
                shortcutsExecuted [i] = true;
            }
        }
    }
}

当然,这个无休止的运行循环constantly consumes some %s of CPU。不好

所以我试图仅在任何进程开始或停止时才调用上面的代码:

// processListChanged event executes code above

ManagementEventWatcher startProcWatcher = new ManagementEventWatcher(
           new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
startProcWatcher.EventArrived += new EventArrivedEventHandler(processListChanged);
startProcWatcher.Start();
ManagementEventWatcher stopProcWatcher = new ManagementEventWatcher(
                new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"));
stopProcWatcher.EventArrived += new EventArrivedEventHandler(processListChanged);
stopProcWatcher.Start();

而且效果很好。现在,程序仅在任何进程已启动或停止时才加载CPU

enter image description here

但是最后一种方法需要管理员权限,因此不适合我。

在没有管理员权限的情况下启动或停止任何进程时,是否可以引发事件?还是有更好的(优化的)解决方案来显示每个快捷方式是否正在运行?

0 个答案:

没有答案