Getting an HWND from a process started with CreateProcess

1
2
3
4
5
6
7
STARTUPINFO si = { sizeof(STARTUPINFO) };
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_NORMAL;
PROCESS_INFORMATION pi;
CreateProcess(L"D:\\pikachu.exe", NULL, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi);
WaitForInputIdle(pi.hProcess, INFINITE);


How to get HWND after opening a game, what should I do next
Last edited on
Use FindWindow() to find the created window using its title and class. Or if the class isn't known use EnumWindows() to find the window with a matching title etc.
I have a lot of windows open so I can't use this method
Don't be silly. Give it a try. (untested code)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
struct ProcHwnd {
    DWORD proc_id;
    HWND  hwnd;
};

BOOL CALLBACK enum_windows_proc(HWND hwnd, LPARAM lParam) {
    DWORD processId;
    GetWindowThreadProcessId(hwnd, &processId);
    if (processId == ((ProcHwnd*)lParam)->proc_id) {
        ((ProcHwnd*)lParam)->hwnd = hwnd;
        return FALSE;
    }
    return TRUE;
}

HWND start_pikachu() {
    STARTUPINFO si;
    si.cb = sizeof si;
    si.dwFlags = STARTF_USESHOWWINDOW;
    si.wShowWindow = SW_NORMAL;

    PROCESS_INFORMATION pi;
    CreateProcess(L"D:\\pikachu.exe", 0, 0, 0, FALSE, 0, 0, 0, &si, &pi);
    // Not sure why you used the CREATE_NO_WINDOW flag so I removed it.
    // It shouldn't be needed in a non-console program.

    // Wait for message loop to start.
    WaitForInputIdle(pi.hProcess, INFINITE);

    // Once the program has started you can look for the window.
    ProcHwnd ph { pi.dwProcessId, 0 };
    EnumWindows(enum_windows_proc, &ph);

    return ph.hwnd;
}

...
HWND pikachuHWND = start_pikachu();


There is not any other realistic method. It seems like you can find it faster than findwindow if you have that PI struct filled in -- you should have its PID or something that may be more searchable or even direct access (I do not know). But at some point you have to dig.
and if you spawn 2 or more of the same thing, its even harder to tell them apart.
and.... Dutch ninjaed in front of me with the way to avoid the find.
Last edited on
Thanks dutch for a perfect example
Thanks jonnin for the comment
Topic archived. No new replies allowed.