首页 > 解决方案 > C++ 在同一进程中获取另一个 Windows Hwnd

问题描述

我制作了一个可以注入应用程序的 dll。我希望该 dll 在同一进程中找到另一个窗口。在这里你可以看到一个例子。控制台主机 (Konsolfönstervärd) 是我注入的 dll,我希望它能够找到锁定示例窗口 hwnd。

任务管理器图片

获取带有窗口标题的句柄非常简单。但我不想仅仅为那个应用程序硬编码它。

HWND parentHandle = FindWindowA(NULL, "Lockdown Example");

我还尝试了一些 EnumWindows 的东西,它基本上打印了所有可见的窗口及其窗口标题。在其输出中,您可以看到“锁定示例”窗口。

10828:  TheDll
388:  Lockdown Example
13380:  Microsoft Store
6664:  Program Manager

我如何让它只在找到“锁定示例”时才做某事,而不仅仅是给它一个硬编码的标题。而是给它类似 GetCurrentProcessId()

static BOOL CALLBACK enumWindowCallback(HWND hWnd, LPARAM lparam) {
    //GetWindowThreadProcessId();

    int length = GetWindowTextLength(hWnd);
    char* buffer = new char[length + 1];
    GetWindowText(hWnd, buffer, length + 1);
    std::string windowTitle(buffer);

    // List visible windows with a non-empty title
    if (IsWindowVisible(hWnd) && length != 0) {

        cout << GetWindowThreadProcessId(hWnd, NULL) << ":  " << windowTitle << endl;
    }
    return TRUE;
}

EnumWindows(enumWindowCallback, NULL)

标签: c++windows

解决方案


所以我想出了一个答案,稍微修改一下 enumWindowCallback 。

BOOL CALLBACK enumWindowCallback(HWND hwnd, LPARAM lParam)
{
    int length = GetWindowTextLength(hwnd);
    char* buffer = new char[length + 1];
    GetWindowText(hwnd, buffer, length + 1);
    std::string windowTitle(buffer);

    DWORD lpdwProcessId;
    GetWindowThreadProcessId(hwnd, &lpdwProcessId);

    // 1. Checks if the current process is not equals to the value given in the lParam
    // 2. Check if the current window is visible
    // 3. Check if its not a empty name
    // 4. Check so it is not the console window
    // All these filters result in to only show all visible windows in the process
    // Which in my case is "17260 | 15800:  Lockdown Example"
    if (lpdwProcessId == lParam && IsWindowVisible(hwnd) && length != 0 
        && GetWindowThreadProcessId(GetConsoleWindow(), NULL) != GetWindowThreadProcessId(hwnd, NULL))
    {
        // Here you can do anything with the window handle (hwnd)
        cout << lpdwProcessId << " | "<< GetWindowThreadProcessId(hwnd, NULL) << ":  " << windowTitle << endl;
    }
    return TRUE;
}

调用它:

EnumWindows(enumWindowCallback, GetCurrentProcessId()); // iterate over all windows

推荐阅读