macOS 定期向活动应用程序发送击键

macOS send keystroke to the active app periodically

我正在尝试每分钟向一个名为 "Dbeaver" 的 macOS (Mojave) 应用程序发送击键 (command+ shift+ r) 只要 DBeaver 是活动应用程序.我试过以下没有效果。

tell application "System Events"
    set activeApp to name of first application process whose frontmost is true
    if "DBeaver" is in activeApp then
        tell application "System Events" to keystroke "r" using {command down, shift down}

    end if
end tell

如果脚本像下面这样简单,它就可以完美运行:

activate application "DBeaver" 
tell application "System Events" to keystroke "r" using {command down, shift down}

我没有您提到的应用程序,但我使用 TextEdit.app 按照 AppleScript 代码测试了它并且它有效。如果您 运行 遇到任何错误或问题,请告诉我

tell application "System Events"
    repeat while (exists of application process "DBeaver")
        set activeApp to name of first application process whose frontmost is true
        if "DBeaver" is in activeApp then
            tell its application process "DBeaver"
                repeat while frontmost
                    keystroke "r" using {command down, shift down}
                    delay 60
                end repeat
            end tell
        end if
    end repeat
end tell

您要避免使用 repeat 循环之类的东西,因为这会阻塞应用程序的用户界面(用于退出或只是为了避免死亡的旋转轮)。重复这样的事情的一种相对简单的方法是制作一个保持打开的应用程序,并将重复代码放在使用计时器的 idle 处理程序中 - 例如:

on idle
    tell application "System Events"
        set activeApp to name of first application process whose frontmost is true
        if "DBeaver" is in activeApp then
            tell application "System Events" to keystroke "r" using {command down, shift down}
        end if
    end tell
    return 60 -- do it again in 60 seconds
end

idle 处理程序中的语句是 运行 当应用程序空闲时; return 值确定处理程序再次 运行 之前的秒数。