c++ - 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)
解决方案
所以我想出了一个答案,稍微修改一下 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
推荐阅读
- python-3.x - nltk frequency_distribution.max() 需要多个结果
- python - 如何在特定位置或特定相交 matplotlib 处相交?
- r - 计算这种情况下的时间差
- python - 如何在 Python 中对小数位进行运算
- java - Integer.parseInt(string) 有问题
- php - Tempo OAuth 2.0 令牌
- angular - 带有 rxjs 7.4 和 TS 4+ 的 Angular13 给出错误....找不到模块“rxjs”的声明文件
- three.js - Three.js 是否支持更复杂的材质
- mysql - Mysql随机记录使用join
- javascript - 使用 Code Runner 在 VSCode 中运行 .js 函数并获取 ReferenceError:
没有定义