My code takes a screenshot of a program when it becomes the foreground window. Running into a small issue with the timing of the screenshots

StackOverflow https://stackoverflow.com/questions/18880473

  •  29-06-2022
  •  | 
  •  

Question

I have this line of code in my main method:

IntPtr hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, procDelegate, 0, 0, WINEVENT_OUTOFCONTEXT);

Then I have this in my class:

delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);

    static void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
    // filter out non-HWND namechanges... (eg. items within a listbox)
    if (idObject != 0 || idChild != 0)
    {
        return;
    }

    SaveImage(Capture(hwnd), hwnd);
    Console.WriteLine("Handle: {0:x8}", hwnd.ToInt32());
}

I have a small problem with this code and it is very hard to articulate so bear with me. The basic idea behind this code is that I want to take a screenshot of the current application in the foreground and save it to a location on the C drive. So far my code allows me to do this, however it doesn't always work exactly how I want it to. The problem is that sometimes when I click an application (therefore bringing it to the foreground) it will take the picture before the window has had time to completely maximize. This leads to my screenshots folder being filled with screenshots that are of the desktop behind the application.

Is there a way to wait until the window is completely maximized before I call my screenshot function?

Was it helpful?

Solution

You can use SetWindowsHookEx with WH_CALLWNDPROCRET to know when WM_PAINT has been processed by the window. Or you can hack it by delaying a bit before taking your screenshot, which from a practical standpoint might be all you really need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top