为何点击对话框Cancel按钮时我的AppleScript不退出?
AppleScript自定义对话框Cancel按钮不中断脚本的解决方法
问题原因
当你自定义buttons参数时,AppleScript不会自动把写死的"Cancel"按钮当成系统级取消操作——尤其你的系统语言非英语时,系统默认的取消按钮是本地化后的文本,不是英文"Cancel",所以点击这个自定义按钮只会返回按钮名称,不会触发中断脚本的错误。而不带自定义按钮的display dialog用的是系统默认本地化按钮,点击取消时会抛出用户取消的错误,直接中断脚本。
解决方法
方法一:判断按钮返回值,主动抛出中断错误
捕获对话框的返回结果,判断如果点击的是"Cancel",就抛出AppleScript标准的用户取消错误码,让脚本直接中断:
set theResponse to display dialog "Name?" default answer myname with icon note buttons {"Cancel", "Continue"} default button "Continue" if button returned of theResponse is "Cancel" then error number -128 end if
error number -128是AppleScript内置的用户取消操作错误码,抛出后脚本会立刻停止,和系统默认对话框的行为完全一致。
方法二:使用本地化按钮文本并指定取消按钮
通过localized string获取系统语言对应的按钮文本,再用cancel button参数明确标记取消按钮,让系统自动识别并触发中断:
set cancelBtn to localized string "Cancel" set continueBtn to localized string "Continue" set theResponse to display dialog "Name?" default answer myname with icon note buttons {cancelBtn, continueBtn} default button continueBtn cancel button cancelBtn
这样对话框会显示符合你系统语言的按钮文本,点击取消按钮时会自动中断脚本,无需额外判断。
内容的提问来源于stack exchange,提问作者d-b
相关产品推荐
相关产品推荐

