AppleScript如何检测GUI指定按钮点击并终止脚本?
你原有代码的核心错误是误用了button returned属性,这个属性仅属于display dialog命令的返回结果,普通GUI按钮没有这个属性,所以你永远拿不到点击状态,加上空的try块吞掉了所有报错,你也看不到问题提示,同时循环没有加延迟会占满CPU资源。
以下是修复后的可运行代码:
-- 请替换为你实际操作的GUI应用的名称 set targetApp to "替换为你的目标应用名" tell application "System Events" tell process targetApp repeat while exists progress indicator 1 of sheet 1 -- 加0.2秒延迟,避免占用过多CPU资源 delay 0.2 if exists button "Stop" of sheet 1 then -- 若你点击Stop后按钮会变为不可用,用AXEnabled属性判断 if value of attribute "AXEnabled" of button "Stop" of sheet 1 is false then display dialog "Operation cancelled" error number -128 end if else -- 若点击Stop后按钮会直接消失,进入该分支触发取消逻辑 display dialog "Operation cancelled" error number -128 end if end repeat end tell end tell
注意:运行前需要给执行脚本的程序(脚本编辑器、终端、打包后的独立app等)开启系统「隐私与安全性」-「辅助功能」权限,否则无法操作其他应用的GUI元素。
内容的提问来源于stack exchange,提问作者userX
相关产品推荐
相关产品推荐

