Get hwnd by process id c++

2020-02-05 19:17发布

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.

标签: c++ get pid hwnd
4条回答
beautiful°
2楼-- · 2020-02-05 19:49
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);
查看更多
男人必须洒脱
3楼-- · 2020-02-05 19:49

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.

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);
}
查看更多
爷的心禁止访问
4楼-- · 2020-02-05 19:51

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);
}
查看更多
放我归山
5楼-- · 2020-02-05 19:53

You can use EnumWindows and GetWindowThreadProcessId() functions as mentioned in this MSDN article.

查看更多
登录 后发表回答