通过进程ID获取hwnd C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11711417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get hwnd by process id c++
提问by Luke
How can I get the HWND of application, if I know the process ID? Anyone could post a sample please? I'm using MSV C++ 2010. I found Process::MainWindowHandle but I don't know how to use it.
如果我知道进程 ID,如何获取应用程序的 HWND?任何人都可以张贴样品吗?我使用的是 MSV C++ 2010。我找到了 Process::MainWindowHandle 但我不知道如何使用它。
回答by Andre Kirpitch
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);
回答by PermanentGuest
You can use EnumWindows and GetWindowThreadProcessId() functions as mentioned in this MSDN article.
您可以使用此MSDN 文章中提到的 EnumWindows 和 GetWindowThreadProcessId() 函数。
回答by Michael Haephrati
A single PID (Process ID) can be associated with more than one window (HWND). For example if the application is using several windows.
The following code locates the handles of all windows per a given PID.
单个 PID(进程 ID)可以与多个窗口 (HWND) 相关联。例如,如果应用程序使用多个窗口。
以下代码根据给定的 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);
}
回答by rsarov
Thanks to Michael Haephrati, I slightly corrected your code for modern Qt C++ 11:
感谢Michael Haephrati,我稍微更正了现代 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);
}