开发者

GetForegroundWindow() with Ticker C# - Reduce CPU Usage

I am creating a program that will monitor computer usage. Part of this program requires that I know at all times what the foreground window is. That is achieved by this code:

    // Returns the name of the process owning the foreground window.
    private static Process 开发者_如何学PythonGetForegroundProcess()
    {
        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;
        }
    }

The problem I am having is CPU consumption. This gradually uses all of my CPU because it is called within a ticker that ticks every second. Ticking every second is necessary for core functionality in the program.

My question then would be, is there a way to go about this without having my program freeze up the computer?

Thanks for your time and responses!


Disable the timer when you're code is running!. If its slower then the timer it'll lock up you're system. Execute the code on a background thread and see if there is a different API to get the same information that works better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜