AppleScript窗口缩放应用:解决Spotlight启动时前置应用识别错误
问题原因
当通过Spotlight启动lhalf.app时,该应用会自动成为当前最前端进程,但它本身没有任何窗口,导致你的代码尝试获取它的窗口时触发「无效索引」错误。而在Script Editor中测试时,脚本取的是Script Editor自身的窗口,因此不会报错。
修正方案:排除自身进程,定位目标应用
修改AppleScript代码,通过排除自身进程+筛选最近激活的带窗口应用,精准定位到你真正需要调整的前置应用:
tell application "System Events" -- 获取当前.app的进程名(自动匹配打包后的名字) set myAppName to name of current application -- 筛选规则:排除自身、必须有窗口,按最后激活时间倒序排列 set targetApps to every application process whose name is not myAppName and windows is not {} set sortedApps to sort targetApps by last activated date descending -- 取最近激活的目标应用 set targetApp to item 1 of sortedApps -- 将目标应用设为前台(确保窗口操作生效) set frontmost of targetApp to true -- 获取目标应用的主窗口 set mainWindow to first window of targetApp whose value of attribute "AXMain" is true -- 设置窗口位置与尺寸 set position of mainWindow to {0, 22} set size of mainWindow to {800, 600} end tell
必要配置:开启辅助功能权限
因为脚本需要控制其他应用的窗口,必须给lhalf.app开启系统权限:
- 打开「系统设置」→「隐私与安全性」→「辅助功能」
- 点击右下角锁图标解锁,点击「+」按钮
- 找到并添加你的
lhalf.app,开启权限开关
更优实现:加入错误处理
为避免无符合条件应用时静默报错,可添加错误捕获逻辑:
try tell application "System Events" set myAppName to name of current application set targetApps to every application process whose name is not myAppName and windows is not {} if targetApps is {} then error "没有可调整窗口的应用" end if set sortedApps to sort targetApps by last activated date descending set targetApp to item 1 of sortedApps set frontmost of targetApp to true set mainWindow to first window of targetApp whose value of attribute "AXMain" is true set position of mainWindow to {0, 22} set size of mainWindow to {800, 600} end tell on error errMsg display dialog "操作失败:" & errMsg buttons {"确定"} default button 1 end try
内容的提问来源于stack exchange,提问作者vicky
相关产品推荐
相关产品推荐

