- 公开视频 -> 链接点击跳转公开课程
- 博客首页 -> 链接点击跳转博客主页
目录
[EnumWindows: 枚举系统中的所有顶层窗口,并将句柄传递给回调函数。](#EnumWindows: 枚举系统中的所有顶层窗口,并将句柄传递给回调函数。)
[EnumChildWindows: 枚举指定父窗口的所有子窗口,并将句柄传递给回调函数。](#EnumChildWindows: 枚举指定父窗口的所有子窗口,并将句柄传递给回调函数。)
窗口层次结构
EnumWindows: 枚举系统中的所有顶层窗口,并将句柄传递给回调函数。
cpp
EnumWindows(EnumWindowsProc, 0);
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lparam)
{
TCHAR szTitleName[0xFF] = { 0 };
TCHAR szClassName[0xFF] = { 0 };
GetWindowText(hwnd, szTitleName, 0xFF);
GetClassName(hwnd, szClassName, 0xFF);
printf("顶层窗口句柄 -> %p 标题 -> %ws 类名 -> %ws \r\n", hwnd, szTitleName, szClassName);
return TRUE;
}
EnumChildWindows: 枚举指定父窗口的所有子窗口,并将句柄传递给回调函数。
cpp
EnumChildWindows(hwndMain, EnumChildWindowsProc, 0);
BOOL CALLBACK EnumChildWindowsProc(HWND hwnd, LPARAM lparam)
{
TCHAR szTitleName[0xFF] = { 0 };
TCHAR szClassName[0xFF] = { 0 };
GetWindowText(hwnd, szTitleName, 0xFF);
GetClassName(hwnd, szClassName, 0xFF);
printf("子窗口句柄 -> %p 标题 -> %ws 类名 -> %ws \r\n", hwnd, szTitleName, szClassName);
return TRUE;
}
窗口状态和属性
- 有效性检查 (
IsWindow
):任何操作之前,必须首先确定窗口句柄是否有效。 - 可见性检查 (
IsWindowVisible
):决定窗口是否显示在屏幕上。 - 启用/禁用窗口 (
EnableWindow
):控制用户对窗口的交互能力。 - 状态检查 (
IsIconic
/IsZoomed
):确定窗口当前是否处于最小化或最大化状态。
cpp
#include <windows.h>
#include <iostream>
#include <vector>
#include <string>
// 结构体用来保存窗口信息
struct WindowInfo {
HWND hWnd;
std::string title;
std::string className;
BOOL isWindow;
BOOL isVisible;
BOOL isEnabled;
BOOL isMinimized;
BOOL isMaximized;
};
// 回调函数用于枚举窗口
BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) {
std::vector<WindowInfo>* pWindowList = reinterpret_cast<std::vector<WindowInfo>*>(lParam);
char title[256];
char className[256];
// 获取窗口标题
GetWindowTextA(hWnd, title, sizeof(title));
// 获取窗口类名
GetClassNameA(hWnd, className, sizeof(className));
WindowInfo winInfo;
winInfo.hWnd = hWnd;
winInfo.title = title;
winInfo.className = className;
winInfo.isWindow = IsWindow(hWnd);
winInfo.isVisible = IsWindowVisible(hWnd);
winInfo.isEnabled = IsWindowEnabled(hWnd);
winInfo.isMinimized = IsIconic(hWnd);
winInfo.isMaximized = IsZoomed(hWnd);
pWindowList->push_back(winInfo);
return TRUE;
}
// 获取所有窗口信息的函数
std::vector<WindowInfo> getAllWindows() {
std::vector<WindowInfo> windowList;
EnumWindows(EnumWindowsProc, reinterpret_cast<LPARAM>(&windowList));
return windowList;
}
int main() {
std::vector<WindowInfo> windows = getAllWindows();
for (const auto& win : windows) {
std::cout << "HWND: " << win.hWnd
<< ", Title: " << win.title
<< ", Class: " << win.className
<< ", IsWindow: " << (win.isWindow ? "Yes" : "No")
<< ", Visible: " << (win.isVisible ? "Yes" : "No")
<< ", Enabled: " << (win.isEnabled ? "Yes" : "No")
<< ", Minimized: " << (win.isMinimized ? "Yes" : "No")
<< ", Maximized: " << (win.isMaximized ? "Yes" : "No")
<< std::endl;
}
return 0;
}