我在尝试运行以下代码时遇到问题:
#include "header.h"
int main()
{
id = GetCurrentProcessId();
EnumWindows(hEnumWindows, NULL);
Sleep(5000);
//MoveWindow(hThis, 450, 450, 100, 100, TRUE);
system("pause");
return 0;
}
//header.h
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <Windows.h>
using namespace std;
DWORD id = 0;
HWND hThis = NULL;
BOOL CALLBACK hEnumWindows(HWND hwnd, LPARAM lParam)
{
DWORD pid = 0;
pid = GetWindowThreadProcessId(hwnd, NULL);
if (pid == id)
{
hThis = GetWindow(hwnd, GW_OWNER);
if (!hThis)
{
cout << "Error getting window!" << endl;
}
else
{
char *buffer = nullptr;
int size = GetWindowTextLength(hThis);
buffer = (char*)malloc(size+1);
if (buffer != nullptr)
{
GetWindowText(hThis, buffer, size);
cout << pid << ":" << buffer << endl;
free(buffer);
}
}
}
return TRUE;
}
当我运行这段代码时,屏幕上几乎没有任何输出,就好像程序没有被附加一样。我尝试在 VS2013
的控制台和 Windows 子系统下运行它。
最佳答案
根据GetCurrentProcessId
docs , 应用程序接口(interface)
Retrieves the process identifier of the calling process.
GetWindowThreadProcessId
,另一方面,
Retrieves the identifier of the thread that created the specified window and, optionally, the identifier of the process that created the window.
The return value is the identifier of the thread that created the window.
所以看看你的电话:
pid = GetWindowThreadProcessId(hwnd, NULL);
您实际上得到的是线程 ID,而不是进程 ID。因此,当您将 pid
与 id
进行比较时,您是在比较进程 ID 和线程 ID,这是行不通的。试试这个:
GetWindowThreadProcessId(hwnd, &pid);
(注意:我无法实际测试这是否有效,因为 EnumWindows
需要一个顶级窗口来枚举,我将其作为控制台应用程序运行。如果这个答案无效,请告诉我'不适合你,我会删除它。)
(作为第二个注意事项,您不再需要使用 NULL
,即使对于像 HWND
这样的 WinAPI 东西也是如此。nullptr
将起作用非常好。)
关于c++ - 枚举窗口时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22924627/