c++windowswinapi

What's the reason for the ShowWindow() can't maximize the window?


I want to create a process in fullscreen mode. I've tried setting STARTUPINFO when calling CreateProcess() as follows:

WCHAR cmd = L"Calc";
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(STARTUPINFO));
ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindows = SW_MAXIMIZE;
// or si.dwFlags = STARTF_RUNFULLSCREEN;
BOOL isCreated = CreateProcess(nullptr, cmd,
    nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi);

but the process didn't start in fullscreen mode as expected.

So I tried to obtain its HWND after creating process like this:

HWND FindMainWindow(DWORD processId) {
    struct ProcHwnd {
        DWORD   process_id;
        HWND    hwnd;
    };
    ProcHwnd hProcWnd;
    auto EnumWindowCallback = [](HWND hwnd, LPARAM lParam) -> BOOL {
        ProcHwnd* data = reinterpret_cast<ProcHwnd *>(lParam);
        DWORD windowProcessID;
        GetWindowThreadProcessId(hwnd, &windowProcessID);
        if (windowProcessID == data->process_id) {
            if (IsWindowVisible(hwnd)) {
                data->hwnd = hwnd;
                return false;
            }
        }
        return true;
    };
    EnumWindows(EnumWindowCallback, reinterpret_cast<LPARAM>(&hProcWnd));
    return hProcWnd.hwnd;
}

int main() {
    WCHAR cmd = L"Calc";
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(STARTUPINFO));
    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
    si.cb = sizeof(STARTUPINFO);
    BOOL isCreated = CreateProcess(nullptr, cmd,
        nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi);
    WaitForInputIdle(pi.hProcess, INFINITE);
    HWND hWindow = FindMainWindow(pi.dwProcessId);
    if(hWindow == nullptr)
        return -1;
    ShowWindow(hWindow, SW_MAXIMIZE);
    return 0;
}

The exit code is 0. But the ShowWindow() didn't maximize the window.


Solution

  • in FindMainWindow hProcWnd not initialized and EnumWindowCallback not set any flag, that it actually found window. as result is inknown from such code - are FindMainWindow actually found window or not. so if(hWindow == nullptr) have no sense here. need use

    ProcHwnd hProcWnd {};
    

    also calc.exe in modern windows simply exec another process (Calculator.exe) and exit without create any window. so you got or garbage from stack or debug fill like 0xcccccccccccccccc. in any way your code will be not work with app like calc