首页 > 解决方案 > 如果没有输入操作,如何在超时后自动执行带有 2 个按钮的对话框输入?

问题描述

我在启动时在我的 MacBook 上加载了一个 automator.app,它将我的 MacBook 连接到我的本地服务器。我使用允许我“连接”或“取消”此脚本的对话框创建它。这一直有效,但有时我希望它会在 60 秒后自动输入“连接”。

我并不真正精通 AppleScript,并且我根据在 Internet 上找到的信息构建了我使用的大部分自动化程序(应用程序)例程,并对其进行修改直到它起作用。以下代码有效。它每 5 秒重绘一次对话框,我只希望在不完全重绘对话框的情况下更新数字(wait_time 变量)。如果我能做到这一点,我可以让它每 1 秒更新一次。接下来更重要的是,当我选择默认按钮“立即连接”时,什么也没有发生。“不连接”按钮似乎工作正常。脚本的这一部分运行后,我连接到本地服务器上的特定文件夹,所有这些工作正常。

set theDialogText1 to "You will be connected to the Local Server in "
set wait_time to "60"
set theDialogText2 to " seconds. If your are not on the Local network; select [Don't Connect]."
repeat wait_time times
    display dialog theDialogText1 & wait_time & theDialogText2 buttons {"Don't Connect", "Connect Now"} default button "Connect Now" cancel button "Don't Connect" giving up after 5
    set wait_time to wait_time - 5
end repeat

我希望它能够像 macOS 中的“关闭”对话框一样工作。显示正在发生的事情,提供一个按钮以更快地运行该操作,提供一个取消该功能的按钮,如果没有收到输入,则在 60 秒内自动运行该功能。

标签: applescriptautomator

解决方案


Applescript 仅提供简单的对话框,然后您无法使用简单的 Applescript 命令显示剩余秒数的倒计时。有一个进度条显示,但该显示没有按钮。

最简单的方法是使用带有指令“在 x 之后放弃”的标准对话框,如果用户之前没有反应,它会在 x 秒后关闭对话框。您只需检查对话框是否已使用 give up boolean = true 关闭,或者检查哪个按钮已用于关闭它。下面的脚本处理 3 种情况(测试等待时间 3 秒)

set wait_time to 3
set feedback to display dialog "test time out" buttons {"Don't connect", "Connect"} giving up after wait_time

if gave up of feedback then
    display alert "no user action after " & wait_time & " seconds."
else if button returned of feedback is "Connect" then
    display alert "User clicks on Connect"
else
    display alert "User clicks on don't connect"
end if

您也可以将其放入处理程序(= 子例程)并将 wait_time 设置为 3 秒并多次调用它。脚本变得有点复杂,这就是我添加一些评论的原因:

set Refresh_time to 3 -- the delay between 2 refresh of the dialog
set wait_time to 21 --total delay for user to decide
set Decision to 0
repeat until (Decision > 0) or (wait_time = 0)
    set Decision to Get_User_Feedback(wait_time, Refresh_time)
    set wait_time to wait_time - Refresh_time
end repeat

display alert "Decision is " & Decision
-- 0 means no answer
-- 1 means Connect
-- 2 means don't connect

-- your program here

on Get_User_Feedback(Remain_time, Step_delay)
    set feedback to display dialog "Do you want to connect. Time left is " & Remain_time & " Sec." buttons {"Don't connect", "Connect"} giving up after Step_delay  
    if gave up of feedback then
        return 0
    else if button returned of feedback is "Connect" then
        return 1
    else
        return 2
    end if
end Get_User_Feedback

Get_User_Feedback 在重复循环中被多次调用。它显示对话框 3 秒,然后关闭并再次调用显示新的剩余时间。在总 wait_time 之后,或者如果用户之前使用了按钮,则重复循环停止。


推荐阅读