Inno Setup中如何通过部分窗口名称查找窗口?
Inno Setup 实现窗口标题的部分匹配查找
默认的FindWindowByWindowName()仅支持精确匹配窗口标题,无法直接实现部分匹配或通配符匹配。要处理标题包含动态文件名的场景,需要通过调用Windows原生API遍历所有窗口,检查标题是否包含目标子串。
实现代码示例
在Inno Setup的[Code]段中添加以下代码,自定义一个支持子串匹配的窗口查找函数:
[Code] type TWindowEnumProc = function(hWnd: HWND; lParam: LPARAM): BOOL; stdcall; function EnumWindows(lpEnumFunc: TWindowEnumProc; lParam: LPARAM): BOOL; stdcall; external 'EnumWindows@user32.dll stdcall'; function GetWindowTextLength(hWnd: HWND): Integer; stdcall; external 'GetWindowTextLengthW@user32.dll stdcall'; function GetWindowText(hWnd: HWND; lpString: String; nMaxCount: Integer): Integer; stdcall; external 'GetWindowTextW@user32.dll stdcall'; function IsWindowVisible(hWnd: HWND): BOOL; stdcall; external 'IsWindowVisible@user32.dll stdcall'; var TargetSubstring: string; FoundWindowHandle: HWND; function EnumWindowCallback(hWnd: HWND; lParam: LPARAM): BOOL; stdcall; var WindowText: string; TextLength: Integer; begin Result := True; // 默认继续枚举,找到目标后停止 // 仅检查可见窗口(可根据需求移除该判断) if not IsWindowVisible(hWnd) then Exit; TextLength := GetWindowTextLength(hWnd); if TextLength = 0 then Exit; // 获取窗口标题内容 SetLength(WindowText, TextLength); GetWindowText(hWnd, WindowText, TextLength + 1); // 不区分大小写匹配子串,如需区分则替换为 Pos(TargetSubstring, WindowText) > 0 if Pos(Uppercase(TargetSubstring), Uppercase(WindowText)) > 0 then begin FoundWindowHandle := hWnd; Result := False; // 找到目标,终止枚举 end; end; // 对外暴露的自定义查找函数:返回标题包含指定子串的窗口句柄 function FindWindowByTitleSubstring(const Substring: string): HWND; begin FoundWindowHandle := 0; TargetSubstring := Substring; EnumWindows(@EnumWindowCallback, 0); Result := FoundWindowHandle; end;
使用方式
在脚本中调用自定义函数,即可查找标题包含目标子串的窗口:
var TargetHWND: HWND; begin // 查找标题包含"文档.txt"的窗口 TargetHWND := FindWindowByTitleSubstring('文档.txt'); if TargetHWND <> 0 then begin // 找到窗口后的操作,比如激活窗口 // ShowWindow(TargetHWND, SW_RESTORE); // SetForegroundWindow(TargetHWND); end else begin // 未找到窗口的处理逻辑 end; end;
扩展说明
- 如果需要通配符匹配(如
*report*.pdf),可以扩展EnumWindowCallback中的匹配逻辑,实现支持*(任意字符)和?(单个字符)的通配符判断函数。 - 若不需要限定可见窗口,直接删除
IsWindowVisible的判断即可。 - 代码中使用
GetWindowTextW确保支持Unicode编码的窗口标题,适配多语言场景。
内容的提问来源于stack exchange,提问作者user3161924
相关产品推荐
相关产品推荐

