Maximize/Minimize window from another thread

Tabaqui picture Tabaqui · Jul 4, 2015 · Viewed 7.4k times · Source

I'm trying to find out the correct way to minimize/maximize a window owned by another thread. My target window can be fullscreen or not (i should be able to minimize and maximize it regardless of its state). I've tried various combinations of ShowWindow SW_MINIMIZE, SW_MAXIMIZE, SW_FORCEMINIMIZE etc... but the only result i've been able to achieve was restoring it (maximizing) when it was minimized AND fullscreen with ShowWindow(hWnd, SW_RESTORE).

Here it is the code i'm using to retrieve my handle:

#include <Windows.h>
#include <iostream>

// I'm a console application
int main(int argc, char* argv[]) {
    HWND hWnd = FindWindow(TEXT("MyWindowClass"), NULL);
    if(IsWindow(hWnd)) {
        std::cout << "Window found!" << std::endl;
        SetForegroundWindow(hWnd); // I'll give focus to my window. This is always working.
        if(IsIconic(hWnd))
            ShowWindow(hWnd, SW_RESTORE); // This is working only if the window is minimized while in fullscreen mode
        Sleep(3000);
        ShowWindow(hWnd, SW_MINIMIZE); // Not working. SW_FORCEMINIMIZE, SW_HIDE etc are not working either.
    }
    return 0;
}

Answer

Tabaqui picture Tabaqui · Jul 5, 2015

After struggling for a whole day I've found a solution that works for both minimizing and maximizing the window regardless of its state: Post/SendMessage.

To maximize it:

PostMessage(hWnd, WM_SYSCOMMAND, SC_RESTORE, 0);

To minimize it:

PostMessage(hWnd, WM_SYSCOMMAND, SC_MINIMIZE, 0);