Skip to content

Instantly share code, notes, and snippets.

@hasherezade
Last active May 14, 2024 15:45
Show Gist options
  • Save hasherezade/377f1f9fc37d101b4d6c04411b1df497 to your computer and use it in GitHub Desktop.
Save hasherezade/377f1f9fc37d101b4d6c04411b1df497 to your computer and use it in GitHub Desktop.
Find GUI thread
HANDLE find_thread(HANDLE hProcess, DWORD thAccess, bool guiOnly)
{
DWORD targetPid = GetProcessId(hProcess);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
THREADENTRY32 thEntry = { sizeof(THREADENTRY32) };
GUITHREADINFO gui = { 0 };
gui.cbSize = sizeof(GUITHREADINFO);
bool isGUIProcess = false;
DWORD uiFlags = 0;
if (GetGuiResources(hProcess, uiFlags)) {
isGUIProcess = true;
std::cout << "The process is GUI\n";
} else if (guiOnly) {
std::cout << "The process is not GUI\n";
return NULL;
}
std::vector<DWORD> threads;
if (Thread32First(snapshot, &thEntry)) {
do {
if (thEntry.th32OwnerProcessID == targetPid) {
if (isGUIProcess) {
if (!GetGUIThreadInfo(thEntry.th32ThreadID, &gui)) {
continue;
}
std::cout << "GUI thread: " << thEntry.th32ThreadID << "\n";
}
threads.push_back(thEntry.th32ThreadID);
}
} while (Thread32Next(snapshot, &thEntry));
}
CloseHandle(snapshot);
for (auto itr = threads.begin(); itr != threads.end(); ++itr) {
DWORD threadId = *itr;
HANDLE hThread = OpenThread(thAccess, FALSE, threadId);
if (!hThread || hThread == INVALID_HANDLE_VALUE) {
continue;
}
return hThread;
}
return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment