Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximize/Minimize window from another thread

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;
}
like image 998
Tabaqui Avatar asked Sep 03 '25 09:09

Tabaqui


2 Answers

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);
like image 72
Tabaqui Avatar answered Sep 04 '25 22:09

Tabaqui


Try ShowWindow first, and then call SetForegroundWindow:

void show_and_setforeground(HWND hwnd)
{
    WINDOWPLACEMENT place;
    memset(&place, 0, sizeof(WINDOWPLACEMENT));
    place.length = sizeof(WINDOWPLACEMENT);
    GetWindowPlacement(hwnd, &place);

    switch (place.showCmd)
    {
    case SW_SHOWMAXIMIZED:
        ShowWindow(hwnd, SW_SHOWMAXIMIZED);
        break;
    case SW_SHOWMINIMIZED:
        ShowWindow(hwnd, SW_RESTORE);
        break;
    default:
        ShowWindow(hwnd, SW_NORMAL);
        break;
    }

    SetForegroundWindow(hwnd);
}

In addition to IsWindow(hWnd) you may want to use IsWindowVisible(hWnd) because some programs use invisible windows which are not meant to be used.

hwnd = FindWindow(TEXT("MyWindowClass"), NULL);
if (IsWindow(hwnd))
{
    if(IsWindowVisible(hwnd))//optional
    {
        show_and_setforeground(hwnd);
        ...
    }
}
like image 30
Barmak Shemirani Avatar answered Sep 04 '25 21:09

Barmak Shemirani