简体   繁体   English

通过进程ID获取hwnd C++

[英]Get hwnd by process id c++

How can I get the HWND of application, if I know the process ID?如果我知道进程 ID,如何获取应用程序的 HWND? 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.我正在使用 MSV C++ 2010。我找到了 Process::MainWindowHandle 但我不知道如何使用它。

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);

A single PID (Process ID) can be associated with more than one window (HWND).单个 PID(进程 ID)可以与多个窗口(HWND)相关联。 For example if the application is using several windows.例如,如果应用程序使用多个窗口。
The following code locates the handles of all windows per a given PID.以下代码根据给定的 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 dwProcID = 0;
        GetWindowThreadProcessId(hCurWnd, &dwProcID);
        if (dwProcID == dwProcessID)
        {
            vhWnds.push_back(hCurWnd);  // add the found hCurWnd to the vector
            wprintf(L"Found hWnd %d\n", hCurWnd);
        }
    }
    while (hCurWnd != NULL);
}

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);
}

You can use EnumWindows and GetWindowThreadProcessId() functions as mentioned in this MSDN article .您可以使用此MSDN 文章中提到的 EnumWindows 和 GetWindowThreadProcessId() 函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM