枚举窗口 - EnumWindow
函数简介
根据指定条件,枚举系统中符合条件的窗口。该函数可以用于查找特定窗口、获取窗口列表、查找子窗口等操作,支持多种过滤条件组合使用。
接口名称
EnumWindow
DLL调用
long EnumWindow(long ola, long parent, string title, string class_name, int filter)
参数定义:
ola
(长整型数): OLAPlug对象的指针,由 CreateCOLAPlugInterFace 接口生成。parent
(长整型数): 父窗口句柄,获取的窗口必须是该窗口的子窗口。当为0时获取桌面的子窗口。title
(字符串): 窗口标题,支持模糊匹配。如果为空字符串,则不匹配标题。class_name
(字符串): 窗口类名,支持模糊匹配。如果为空字符串,则不匹配类名。filter
(整型数): 过滤条件,可以组合使用(值相加):- 1: 匹配窗口标题(参数title有效)
- 2: 匹配窗口类名(参数class_name有效)
- 4: 只匹配第一个进程的窗口
- 8: 匹配顶级窗口(所有者窗口为0)
- 16: 匹配可见窗口
示例:
// 查找所有可见的顶级窗口,标题包含"记事本"
long strPtr = EnumWindow(ola, 0, "记事本", "", 1 + 8 + 16);
if (strPtr != 0) {
char* hwndList = (char*)strPtr;
printf("找到记事本窗口:%s\n", hwndList);
// 解析窗口句柄列表
char* hwnd = strtok(hwndList, ",");
while (hwnd != NULL) {
printf("窗口句柄:%s\n", hwnd);
hwnd = strtok(NULL, ",");
}
// 释放内存
FreeStringPtr(strPtr);
}
// 查找指定父窗口下所有可见的子窗口,类名包含"Button"
strPtr = EnumWindow(ola, parent_hwnd, "", "Button", 2 + 16);
if (strPtr != 0) {
char* hwndList = (char*)strPtr;
printf("找到按钮窗口:%s\n", hwndList);
// 解析窗口句柄列表
char* hwnd = strtok(hwndList, ",");
while (hwnd != NULL) {
printf("按钮句柄:%s\n", hwnd);
hwnd = strtok(NULL, ",");
}
// 释放内存
FreeStringPtr(strPtr);
}
// 查找所有可见的顶级窗口
strPtr = EnumWindow(ola, 0, "", "", 8 + 16);
if (strPtr != 0) {
char* hwndList = (char*)strPtr;
printf("所有可见顶级窗口:%s\n", hwndList);
FreeStringPtr(strPtr);
}
COM调用
string EnumWindow(long parent, string title, string class_name, int filter)
参数定义:
parent
(长整型数): 父窗口句柄,获取的窗口必须是该窗口的子窗口。当为0时获取桌面的子窗口。title
(字符串): 窗口标题,支持模糊匹配。如果为空字符串,则不匹配标题。class_name
(字符串): 窗口类名,支持模糊匹配。如果为空字符串,则不匹配类名。filter
(整型数): 过滤条件,可以组合使用(值相加):- 1: 匹配窗口标题(参数title有效)
- 2: 匹配窗口类名(参数class_name有效)
- 4: 只匹配第一个进程的窗口
- 8: 匹配顶级窗口(所有者窗口为0)
- 16: 匹配可见窗口
示例:
# 查找所有可见的顶级窗口,标题包含"记事本"
hwnd_list = ola.EnumWindow(0, "记事本", "", 1 + 8 + 16)
if hwnd_list:
hwnd_array = hwnd_list.split(",")
for hwnd in hwnd_array:
messagebox("找到记事本窗口,句柄:" + hwnd)
# 查找指定父窗口下所有可见的子窗口,类名包含"Button"
hwnd_list = ola.EnumWindow(parent_hwnd, "", "Button", 2 + 16)
if hwnd_list:
hwnd_array = hwnd_list.split(",")
for hwnd in hwnd_array:
messagebox("找到按钮窗口,句柄:" + hwnd)
# 查找所有可见的顶级窗口
hwnd_list = ola.EnumWindow(0, "", "", 8 + 16)
if hwnd_list:
hwnd_array = hwnd_list.split(",")
messagebox("系统中共有 " + str(len(hwnd_array)) + " 个可见顶级窗口")
返回值
字符串:
- 返回所有匹配的窗口句柄字符串,格式为"hwnd1,hwnd2,hwnd3"
- 如果没有找到匹配的窗口,返回空字符串
注意事项
- DLL调用返回字符串指针地址,需要调用 FreeStringPtr 接口释放内存
- 过滤条件可以组合使用,例如:1+8+16 表示匹配标题、顶级窗口和可见窗口
- 某些窗口可能无法被枚举,这取决于当前用户的权限和窗口的状态
- 建议在使用此函数前,先使用 GetWindowTitle 和 GetWindowClass 函数获取窗口信息
- 如果需要查找特定进程的窗口,可以使用 EnumWindowByProcess 函数