通过进程找窗口 - FindWindowByProcess
函数简介
根据进程名称、窗口类名和标题查找可见窗口。此函数提供了一种灵活的方式来定位特定进程的窗口。
接口名称
FindWindowByProcess
DLL调用
long FindWindowByProcess(long ola, string process_name, string class, string title)
参数定义:
ola
(长整型数): OLAPlug对象的指针,由 CreateCOLAPlugInterFace 接口生成。process_name
(字符串): 进程名称(如"notepad.exe"),精确匹配但不区分大小写。class
(字符串): 窗口类名,支持模糊匹配。如果为空字符串(""),则匹配所有类名。title
(字符串): 窗口标题,支持模糊匹配。如果为空字符串(""),则匹配所有标题。
示例:
// 查找记事本进程的主窗口
long hwnd = FindWindowByProcess(ola, "notepad.exe", "", "记事本");
if (hwnd != 0) {
printf("Found Notepad window: %ld\n", hwnd);
// 验证找到的窗口
if (GetWindowState(ola, hwnd, 2) == 1) { // 检查是否可见
printf("Window is visible\n");
// 获取完整的窗口标题
char title[256];
GetWindowText(hwnd, title, sizeof(title));
printf("Full window title: %s\n", title);
}
} else {
printf("Notepad window not found\n");
}
// 查找Chrome浏览器的特定窗口
hwnd = FindWindowByProcess(ola, "chrome.exe", "Chrome_WidgetWin_1", "Google");
if (hwnd != 0) {
printf("Found Chrome window: %ld\n", hwnd);
// 检查窗口状态
if (GetWindowState(ola, hwnd, 1) == 1) { // 检查是否激活
printf("Chrome window is active\n");
} else {
printf("Chrome window is not active\n");
}
} else {
printf("Chrome window not found\n");
}
// 查找所有记事本窗口
long hwndArray[10]; // 假设最多存储10个窗口句柄
int count = 0;
hwnd = FindWindowByProcess(ola, "notepad.exe", "", "");
while (hwnd != 0 && count < 10) {
hwndArray[count++] = hwnd;
printf("Found Notepad window %d: %ld\n", count, hwnd);
// 继续查找下一个窗口
hwnd = FindWindowByProcess(ola, "notepad.exe", "", "");
}
printf("Total Notepad windows found: %d\n", count);
返回值
长整型数:
- 非零值: 返回找到的窗口句柄
0
: 未找到匹配的窗口
注意事项
- 进程名称必须包含扩展名(如".exe"),且不区分大小写
- 类名和标题支持模糊匹配,可以只包含部分文本
- 空字符串参数会匹配任意值,可用于通配搜索
- 如果有多个匹配的窗口,函数返回第一个找到的窗口
- 建议使用更具体的搜索条件以提高查找准确性
- 某些系统进程的窗口可能无法被找到
- 进程必须具有可见的主窗口才能被找到
- 可以结合 GetWindowState 验证找到的窗口