You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让保存为.app的AppleScript循环脚本响应右键退出?

解决Amphetamine控制脚本保存为.app后无法右键退出的问题

你的脚本无法通过右键Quit退出的核心原因是:无限循环repeat while true占据了主线程,且没有响应系统的退出事件请求。当你点击Quit时,系统发送的退出信号无法被脚本处理,导致程序卡住。

以下是修复后的脚本:

-- 全局变量控制循环状态
set keepRunning to true

-- 处理系统退出事件
on quit
    set keepRunning to false
    tell application "Amphetamine" to end session
    continue quit -- 执行默认退出流程
end quit

-- 初始启动Amphetamine会话
tell application "Amphetamine" to start new session with options {duration:5, interval:minutes, displaySleepAllowed:false}

repeat while keepRunning
    tell application "Amphetamine" to start new session with options {duration:5, interval:minutes, displaySleepAllowed:false}
    
    -- 检测开盖状态
    set lid to do shell script "ioreg -r -k AppleClamshellState -d 4 | grep AppleClamshellState"
    if lid contains "no" then
        set notification to display alert "Keep Mac Awake" message "The lid is opened. Would you like to stop?" buttons ["Continue", "Stop"] default button 2
        if button returned of notification is equal to "Stop" then
            set keepRunning to false
            tell application "Amphetamine" to end session
        end if
    end if
    
    -- 延迟期间允许脚本响应系统事件(比如退出请求)
    delay 290
end repeat

关键修改说明:

  1. 全局变量keepRunning:替代原来的true硬编码,用来控制循环的启停,无论是用户点击Quit还是在弹窗选择Stop,都能通过修改这个变量终止循环。
  2. on quit处理程序:专门响应系统的退出请求,将keepRunning设为false,结束Amphetamine会话后执行默认退出流程,让程序能正常关闭。
  3. 弹窗逻辑同步:当用户在弹窗选择Stop时,同样设置keepRunning为false,保证循环能正常终止。

保存应用的注意事项:

将脚本保存为.app时,必须勾选Stay open after run handler选项(在保存对话框的“Options”里),否则程序会在脚本执行完初始代码后直接退出,无法保持后台运行。

内容的提问来源于stack exchange,提问作者Oneechan69

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 07:51:10