关于AHK中WinGetAll函数多参数传递的技术求助
自定义WinGetAll函数:支持多字段获取与系统窗口过滤
原论坛的WinGetAll函数局限性较强,下面提供一个更灵活的实现,完全满足你多参数获取窗口信息、过滤系统窗口的需求:
WinGetAll(params*) { ; 解析参数:前N个是要获取的字段,最后一个如果是布尔值则为是否跳过系统窗口(默认true) SkipSystemWindows := true if (IsObject(params) && params.MaxIndex() > 0 && IsBoolean(params[params.MaxIndex()])) { SkipSystemWindows := params.Pop() } ; 定义支持的字段映射,对应AHK的WinGet命令参数 fieldMap := { "Title": "Title", "Class": "Class", "Hwnd": "ID", "Process": "ProcessName", "PID": "PID" } ; 获取所有顶层窗口句柄 WinGet, windowList, List result := [] ; 遍历每个窗口 Loop, % windowList { hwnd := windowList%A_Index% ; 过滤系统窗口:检查进程名是否在排除列表 if (SkipSystemWindows) { WinGet, procName, ProcessName, ahk_id %hwnd% excludedProcs := ["svchost.exe", "csrss.exe", "services.exe", "lsass.exe", "wininit.exe"] if (excludedProcs.HasKey(procName)) continue } ; 收集当前窗口的指定字段信息 windowInfo := [] for _, field in params { if (fieldMap.HasKey(field)) { WinGet, value, % fieldMap[field], ahk_id %hwnd% windowInfo.Push(value) } else { ; 不支持的字段返回空值 windowInfo.Push("") } } ; 将当前窗口的信息以字符串形式加入结果(用制表符分隔,方便查看) result.Push(StrJoin(windowInfo, "`t")) } ; 返回所有窗口信息的数组,或用换行符拼接成字符串 return result.Length() ? StrJoin(result, "`n") : "" } ; 辅助函数:数组转字符串 StrJoin(arr, sep="") { str := "" for _, elem in arr { str .= (str ? sep : "") . elem } return str }
使用示例
- 获取指定字段且过滤系统窗口:
windowData := WinGetAll("Title", "Class", "Hwnd", "Process", "PID") MsgBox % windowData
- 不过滤系统窗口,获取标题和进程名:
windowData := WinGetAll("Title", "Process", false) MsgBox % windowData
新手友好替代方案
如果你不想用自定义函数,也可以用AHK原生命令分步实现,逻辑更直观,便于调试:
; 获取所有顶层窗口句柄 WinGet, windowList, List result := "" Loop, % windowList { hwnd := windowList%A_Index% ; 过滤系统进程 WinGet, procName, ProcessName, ahk_id %hwnd% if (procName = "svchost.exe" || procName = "csrss.exe") continue ; 逐个获取所需信息 WinGet, title, Title, ahk_id %hwnd% WinGet, className, Class, ahk_id %hwnd% WinGet, pid, PID, ahk_id %hwnd% ; 拼接成一行 result .= title "`t" className "`t" hwnd "`t" procName "`t" pid "`n" } MsgBox % Trim(result, "`n")
这个方案不需要自定义函数,每一步都清晰,适合新手理解窗口信息的获取流程。
内容的提问来源于stack exchange,提问作者gaberiel__
相关产品推荐
相关产品推荐

