Skip to content

Instantly share code, notes, and snippets.

@storycraft
Last active June 17, 2021 07:10
Show Gist options
  • Save storycraft/56ca1506403cc945d19219701ebb04a6 to your computer and use it in GitHub Desktop.
Save storycraft/56ca1506403cc945d19219701ebb04a6 to your computer and use it in GitHub Desktop.
Find main window of given process id
#include <windows.h>
HWND FindMainWindow(DWORD pid) {
HANDLE threadSnap = INVALID_HANDLE_VALUE;
threadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, pid);
if(threadSnap == INVALID_HANDLE_VALUE) return NULL;
THREADENTRY32 entry = { sizeof(THREADENTRY32) };
HWND win = NULL;
BOOL CALLBACK enumThreadWinCb(HWND hwnd, LPARAM lParam) {
win = hwnd;
return FALSE;
}
BOOL res;
for (res = Thread32First(threadSnap, &entry); res; res = Thread32Next(threadSnap, &entry)) {
if (entry.th32OwnerProcessID != pid) continue;
EnumThreadWindows(entry.th32ThreadID, enumThreadWinCb, 0);
if (win) break;
}
CloseHandle(threadSnap);
return win;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment