Search code examples
c#timermonitorcpu-usageforeground

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 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;
        }
    }

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!


Solution

  • 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.