如果没有输入操作,如何获得带有 2 个按钮的对话框输入,以便在超时后自动执行?



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

我并不真正精通AppleScript,并且已经根据我在互联网上找到的信息构建了我使用的大部分自动机(应用程序(例程,并对其进行了修改,直到它起作用。以下代码有效,有点。它每 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 秒内自动运行该功能。

Applescript只提供简单的对话框,那么你不能用简单的Applescript命令显示剩余秒数的倒计时。有一个进度条显示,但该显示没有按钮。

最简单的方法是使用带有"在 x 后放弃"指令的标准对话框,如果用户之前没有反应,它会在 x 秒后关闭对话框。您只需要检查对话框是否已使用放弃的布尔值 = 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

您也可以将其放在处理程序(= sub 例程(中,并将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后,或者如果用户之前使用按钮,重复循环将停止。

最新更新