1

我正在创建一个监控计算机使用情况的程序。该程序的一部分要求我始终知道前景窗口是什么。这是通过以下代码实现的:

    // Returns the name of the process owning the foreground window.
    private static Process GetForegroundProcess()
    {
        try
        {
            IntPtr hwnd = GetForegroundWindow();
            // The foreground window can be NULL in certain circumstances, 
            // such as when a window is losing activation.
            uint pid;
            GetWindowThreadProcessId(hwnd, out pid);

            Process p = Process.GetProcessById((int)pid);

            return p;
        }
        catch (Exception)
        {
            return null;
        }
    }

我遇到的问题是 CPU 消耗。这逐渐使用了我所有的 CPU,因为它是在每秒滴答的代码中调用的。程序中的核心功能需要每秒滴答作响。

那么我的问题是,有没有办法在不让我的程序冻结计算机的情况下解决这个问题?

感谢您的时间和回复!

4

1 回答 1

0

代码运行时禁用计时器!如果它的速度较慢,那么它会锁定你的系统。在后台线程上执行代码,看看是否有不同的 API 可以更好地获取相同的信息。

于 2011-03-24T11:18:22.020 回答