枚举窗口时出现问题
Issue when enumerating windows
我在尝试运行以下代码时遇到问题:
#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
文档,API
检索调用进程的进程标识符。
GetWindowThreadProcessId
,另一方面,
检索创建指定窗口的线程的标识符,以及创建该窗口的进程的标识符(可选)。
返回值是创建窗口的线程的标识符。
所以看看你的电话:
pid = GetWindowThreadProcessId(hwnd, NULL);
实际上,你得到的是线程ID,而不是进程ID。所以当你比较pid
和id
时,你比较的是进程ID和线程ID,这是行不通的。试试这个:
GetWindowThreadProcessId(hwnd, &pid);
(注意:我实际上无法测试这是否有效,因为EnumWindows
需要一个顶级窗口来枚举,而我将其作为控制台应用程序运行。如果这个答案不适用,请告诉我,我会删除它。)
(作为第二个注意事项,您不需要再使用NULL
,即使是像HWND
这样的WinAPI。nullptr
也可以很好地工作。)
我假设您正试图从ProcessID中找到"Main"窗口。。在这种情况下,这可能会有所帮助:
#include "stdafx.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <Windows.h>
struct WindowHandleStructure
{
unsigned long PID;
HWND WindowHandle;
};
BOOL CALLBACK EnumWindowsProc(HWND WindowHandle, LPARAM lParam)
{
unsigned long PID = 0;
WindowHandleStructure* data = reinterpret_cast<WindowHandleStructure*>(lParam);
GetWindowThreadProcessId(WindowHandle, &PID);
if (data->PID != PID || (GetWindow(WindowHandle, GW_OWNER) && !IsWindowVisible(WindowHandle)))
{
return TRUE;
}
data->WindowHandle = WindowHandle;
return FALSE;
}
HWND FindMainWindow(unsigned long PID)
{
WindowHandleStructure data = { PID, nullptr };
EnumWindows(EnumWindowsProc, reinterpret_cast<LPARAM>(&data));
return data.WindowHandle;
}
int main()
{
HWND Window = FindMainWindow(GetCurrentProcessId());
std::wstring Buffer(GetWindowTextLength(Window) + 1, L' ');
GetWindowText(Window, &Buffer[0], Buffer.size());
std::wcout << Buffer.c_str() << L"n";
system("pause");
return 0;
}
相关文章:
- 关于如何使用指向主窗口的指针的 QT 问题
- 在C++中的SDL2窗口上显示.bmp时出现问题
- 在包含窗口标头时难以解决循环依赖关系问题
- C++窗口的计划问题
- 恢复Qt窗口大小和位置问题
- 初始化 bgfx 时遇到问题(使用 sdl2 窗口)
- SFML FPS访问窗口事件的问题
- C++可拖动的无边框窗口问题
- 滚动条缩略图跟踪长度 基于图像的水平适合调整窗口大小时出现问题
- 从另一个窗口上的控件获取文本时出现问题
- 当在拖动/调整窗口大小的同时对窗口调用isActive()时,返回false.(X11,问题5.4.0)
- 我遇到此问题,运行程序时出现一个弹出窗口,指出调试断言失败
- 调整窗口大小后交换渲染缓冲区会导致问题
- 窗口创建问题
- 我在窗口中创建名称为 Ñ 的文件夹时遇到问题
- 使用SetParent将窗口嵌入外部进程的各种问题
- 在窗口上使用 clang 链接 msvc 内部函数时出现问题
- 尝试在Qt中获取自定义窗口框架时LNK2019问题
- 使用 CMake 链接到窗口上的静态库时出现问题
- 提升窗口中的安装问题