枚举进程窗口 - EnumWindowByProcessId
函数简介
根据指定进程ID以及其它条件,枚举系统中符合条件的窗口。该函数可以用于查找特定进程的所有窗口,支持多种过滤条件组合使用,如窗口标题、类名、可见性等。
接口名称
EnumWindowByProcessId
DLL调用
long EnumWindowByProcessId(long ola, long pid, string title, string class_name, int filter)
参数定义:
ola
(长整型数): OLAPlug对象的指针,由 CreateCOLAPlugInterFace 接口生成。pid
(长整型数): 进程ID。可以通过 GetWindowProcessId 函数获取。title
(字符串): 窗口标题,支持模糊匹配。如果为空字符串,则不匹配标题。class_name
(字符串): 窗口类名,支持模糊匹配。如果为空字符串,则不匹配类名。filter
(整型数): 过滤条件,可以组合使用(值相加):- 1: 匹配窗口标题(参数title有效)
- 2: 匹配窗口类名(参数class_name有效)
- 4: 只匹配指定进程ID的第一个窗口
- 8: 匹配顶级窗口(所有者窗口为0)
- 16: 匹配可见窗口
示例:
// 查找进程ID为1234的所有可见顶级窗口,标题包含"记事本"
long strPtr = EnumWindowByProcessId(ola, 1234, "记事本", "", 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);
}
// 查找进程ID为5678的所有可见窗口,类名包含"Chrome"
strPtr = EnumWindowByProcessId(ola, 5678, "", "Chrome", 2 + 16);
if (strPtr != 0) {
char* hwndList = (char*)strPtr;
printf("找到Chrome窗口:%s\n", hwndList);
// 解析窗口句柄列表
char* hwnd = strtok(hwndList, ",");
while (hwnd != NULL) {
printf("窗口句柄:%s\n", hwnd);
hwnd = strtok(NULL, ",");
}
// 释放内存
FreeStringPtr(strPtr);
}
// 查找进程ID为1234的第一个可见窗口
strPtr = EnumWindowByProcessId(ola, 1234, "", "", 4 + 16);
if (strPtr != 0) {
char* hwndList = (char*)strPtr;
printf("找到第一个窗口:%s\n", hwndList);
FreeStringPtr(strPtr);
}
COM调用
string EnumWindowByProcessId(long pid, string title, string class_name, int filter)
参数定义:
pid
(长整型数): 进程ID。可以通过 GetWindowProcessId 函数获取。title
(字符串): 窗口标题,支持模糊匹配。如果为空字符串,则不匹配标题。class_name
(字符串): 窗口类名,支持模糊匹配。如果为空字符串,则不匹配类名。filter
(整型数): 过滤条件,可以组合使用(值相加):- 1: 匹配窗口标题(参数title有效)
- 2: 匹配窗口类名(参数class_name有效)
- 4: 只匹配指定进程ID的第一个窗口
- 8: 匹配顶级窗口(所有者窗口为0)
- 16: 匹配可见窗口
示例:
# 查找进程ID为1234的所有可见顶级窗口,标题包含"记事本"
hwnd_list = ola.EnumWindowByProcessId(1234, "记事本", "", 1 + 8 + 16)
if hwnd_list:
hwnd_array = hwnd_list.split(",")
for hwnd in hwnd_array:
messagebox("找到记事本窗口,句柄:" + hwnd)
# 查找进程ID为5678的所有可见窗口,类名包含"Chrome"
hwnd_list = ola.EnumWindowByProcessId(5678, "", "Chrome", 2 + 16)
if hwnd_list:
hwnd_array = hwnd_list.split(",")
for hwnd in hwnd_array:
messagebox("找到Chrome窗口,句柄:" + hwnd)
# 查找进程ID为1234的第一个可见窗口
hwnd_list = ola.EnumWindowByProcessId(1234, "", "", 4 + 16)
if hwnd_list:
hwnd_array = hwnd_list.split(",")
if len(hwnd_array) > 0:
messagebox("找到第一个窗口,句柄:" + hwnd_array[0])
返回值
字符串:
- 返回所有匹配的窗口句柄字符串,格式为"hwnd1,hwnd2,hwnd3"
- 如果没有找到匹配的窗口,返回空字符串
注意事项
- DLL调用返回字符串指针地址,需要调用 FreeStringPtr 接口释放内存
- 过滤条件可以组合使用,例如:1+8+16 表示匹配标题、顶级窗口和可见窗口
- 如果指定了进程ID为0,将枚举所有进程的窗口
- 建议在使用此函数前,先使用 GetWindowProcessId 函数获取正确的进程ID
- 如果需要查找特定进程的所有窗口,可以使用 EnumWindowByProcess 函数