从另一个线程最大化/最小化窗口

时间:2015-07-04 18:48:10

标签: c++ winapi fullscreen minimize maximize

我试图找出最小化/最大化另一个线程拥有的窗口的正确方法。我的目标窗口可以是全屏或不是(我应该能够最小化和最大化它,无论其状态如何)。我尝试过各种ShowWindow SW_MINIMIZE,SW_MAXIMIZE,SW_FORCEMINIMIZE等组合...但我唯一能够实现的结果是在最小化时恢复它(最大化)并使用ShowWindow(hWnd, SW_RESTORE)全屏恢复

这是我用来检索我的句柄的代码:

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

2 个答案:

答案 0 :(得分:2)

经过一整天的努力,我找到了一个解决方案,无论其状态如何,都可以最小化和最大化窗口:Post/SendMessage

最大化它:

PostMessage(hWnd, WM_SYSCOMMAND, SC_RESTORE, 0);

尽量减少它:

PostMessage(hWnd, WM_SYSCOMMAND, SC_MINIMIZE, 0);

答案 1 :(得分:1)

先尝试ShowWindow,然后拨打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);
}

除了IsWindow(hWnd)之外,您可能还想使用IsWindowVisible(hWnd),因为某些程序使用的隐形窗口无意使用。

hwnd = FindWindow(TEXT("MyWindowClass"), NULL);
if (IsWindow(hwnd))
{
    if(IsWindowVisible(hwnd))//optional
    {
        show_and_setforeground(hwnd);
        ...
    }
}