Applescript输入后自动关闭对话框?

时间:2011-07-27 02:42:38

标签: events dialog applescript handler voice-recognition

好的,所以我正在写一个AppleScript来为我做一些语音控制动作。

我正在使用Dragon Dictate 2.0 for mac进行语音控制,主要使用Applecript进行编码。除了曾经的一个小问题,我的所有东西都很平整。当期待语音命令时,我有一个AppleScript显示一个对话框,用于指定文本。

例如。

set cmd1 to the text returned of (display dialog "Speak Command:" default answer "")

这将显示一个带有空文本字段的对话框,以及“取消”和“确定”按钮

我的问题是如何在不说一句话的情况下按下确定。 目前我有一个语音命令,听我说“去”,然后运行一个按下“返回”键的AppleScript。这有效,但我不想说“去”。

我知道我可以添加

giving up after 10

自动关闭对话框并在一段时间后接受输入,但必须有更好的方法。

我做了一些研究,发现我可以有一个“完成编辑”的事件处理程序来执行返回键击。但我不知道该怎么做。如果有人有任何意见或想法会很棒。谢谢!

1 个答案:

答案 0 :(得分:0)

“on done editing”是最好的方法,但是你必须使用objective-c或AppleScriptObjC在Xcode中编写对话框。这似乎超出了你的能力。

可能在你的能力范围内的东西......你可以模拟你自己的“完成编辑”方法。当第一个显示对话框的AppleScript运行时,您可以启动第二个AppleScript。第二个AppleScript可以定期检查对话框的文本字段。当文本停止更改一段时间后,它可以按返回键。这有点复杂,因为你必须弄清楚如何从第二个AppleScript中定位你的对话框,但这不会太难。最好给对话框一个标题,然后使用系统事件找到带有该标题的窗口。

你必须在单独的AppleScript中执行此操作的原因是因为正常的applescript在对话框打开时暂停所有命令。因此,您需要运行单独的进程来检查文本字段,第二个脚本将是最简单的方法。

编辑 :以下是使用applescript的方法。首先创建此脚本,这是您完成的编辑脚本。当用户停止输入文本时,它将关闭您的对话框。将其保存为名为onDoneEditing的脚本到您的桌面。

set shortDelay to 0.5
set longDelay to 1

delay longDelay --delay for a moment to let the dialog box from the first script launch

tell application "System Events"
    set theProcess to first process whose frontmost is true
    tell theProcess
        set dialogWindow to first window

        -- this repeat loop looks for when the user starts entering text into the dialog box
        repeat
            -- get the current text field value
            set currentValue to value of first text field of dialogWindow

            -- if the value has changed we know text is being entered
            if currentValue is not "" then exit repeat

            delay shortDelay
        end repeat

        -- this repeat loop looks for when the user stops entering text
        -- we know that when the text is the same after 2 checks
        delay longDelay
        repeat
            set newValue to value of first text field of dialogWindow

            if newValue is currentValue then
                keystroke return
            else
                set currentValue to newValue
            end if

            delay longDelay
        end repeat
    end tell
end tell

现在创建此脚本。此脚本将使用命令行工具“osascript”启动上述脚本,以便它在后台进程中运行。然后它会显示对话框。您可以在两个脚本中阅读我的注释,以了解每个脚本的工作原理。

-- launch the onDoneEditing script
-- we get the process id (thePID) of the launched process so we can kill it later
set onDoneEditing to (path to desktop as text) & "onDoneEditing.scpt"
set thePID to do shell script "osascript " & quoted form of POSIX path of onDoneEditing & " > /dev/null 2>&1 & echo $!"

-- diaplay the dialog and make sure it will be frontmost
tell me to activate
display dialog "Speak Command:" default answer ""

-- kill the onDoneEditing to make sure it's not still running
try
    do shell script "kill " & thePID
end try