检测AppleScript中的任何击键

时间:2016-09-13 18:16:45

标签: applescript

我希望我的脚本能够通过键盘监听/检测任何按键(按任意键)。如果大约5秒没有按任何键,则继续执行某些操作。否则,继续记录文本编辑中按下的键。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

由于您在问题中指定了TextEdit,因此我为您编写了一个脚本,用于在指定的秒数内检查TextEdit文档中的更改。请注意,这只会检测在文档中输入内容的键,因此它不是完全您想要的内容。但是,无法检测在原始AppleScript中按下的任何键,因此这是您可以获得的最接近的(除非有人编写了脚本添加或代理应用程序来执行此操作)

这是脚本,希望它有用:

global lastText, lastTime, startTime

on run
    set lastText to application "TextEdit"'s (text of the document of the front window)
    set lastTime to current date
    set startTime to current date

    repeat
        if (checkForRecentTextUpdate given seconds:5) is true then
            -- Do something while the user is typing

        else
            -- Do something after the user has stopped typing

            exit repeat -- This is only an example
        end if
    end repeat

end run

to checkForRecentTextUpdate given seconds:secsRequired
    tell application "TextEdit"

        -- If midnight just passed, reset the last time
        if (the day of (the current date)) > (the day of the lastTime) ¬
            then set lastTime to current date

        -- If we just started, we can't judge; give a positive
        if ((the time of (the current date)) - (the time of the startTime)) < secsRequired ¬
            then return true

        -- If there have been changes since the last run, update info
        if (the text of the document of the front window) ≠ the lastText then
            set lastTime to the current date
            set lastText to the text of the document of the front window
        end if

        -- If the specifiied number of seconds has passed without any text updates, give a negative
        if ((the time of (the current date)) - (the time of the lastTime)) ≥ secsRequired ¬
            then return false

        -- If we got this far, there were changes in the seconds specified; give a positive
        return true

    end tell
end checkForRecentTextUpdate