Get hwnd using C ++ process id

How can I get an HWND application if I know the process ID? Can anyone send a sample please? I am using MSV C ++ 2010. I found Process :: MainWindowHandle, but I do not know how to use it.

+8
source share
4 answers
HWND g_HWND=NULL; BOOL CALLBACK EnumWindowsProcMy(HWND hwnd,LPARAM lParam) { DWORD lpdwProcessId; GetWindowThreadProcessId(hwnd,&lpdwProcessId); if(lpdwProcessId==lParam) { g_HWND=hwnd; return FALSE; } return TRUE; } EnumWindows(EnumWindowsProcMy,m_ProcessId); 
+20
source

You can use the EnumWindows and GetWindowThreadProcessId () functions, as indicated in this MSDN article.

+3
source

One PID (process identifier) ​​can be associated with more than one window (HWND). For example, if the application uses multiple windows.
The following code finds all window handles for a given PID.

 void GetAllWindowsFromProcessID(DWORD dwProcessID, std::vector <HWND> &vhWnds) { // find all hWnds (vhWnds) associated with a process id (dwProcessID) HWND hCurWnd = NULL; do { hCurWnd = FindWindowEx(NULL, hCurWnd, NULL, NULL); DWORD dwProcessID = 0; GetWindowThreadProcessId(hCurWnd, &dwProcessID); if (dwProcessID == dwProcessID) { vhWnds.push_back(hCurWnd); // add the found hCurWnd to the vector wprintf(L"Found hWnd %d\n", hCurWnd); } } while (hCurWnd != NULL); } 
+1
source

Thanks to Michael Haephrati , I slightly corrected your code for modern Qt C ++ 11:

 #include <iostream> #include "windows.h" #include "tlhelp32.h" #include "tchar.h" #include "vector" #include "string" using namespace std; void GetAllWindowsFromProcessID(DWORD dwProcessID, std::vector <HWND> &vhWnds) { // find all hWnds (vhWnds) associated with a process id (dwProcessID) HWND hCurWnd = nullptr; do { hCurWnd = FindWindowEx(nullptr, hCurWnd, nullptr, nullptr); DWORD checkProcessID = 0; GetWindowThreadProcessId(hCurWnd, &checkProcessID); if (checkProcessID == dwProcessID) { vhWnds.push_back(hCurWnd); // add the found hCurWnd to the vector //wprintf(L"Found hWnd %d\n", hCurWnd); } } while (hCurWnd != nullptr); } 
0
source

All Articles