如何在 AppleScript 中向菜单栏应用程序(没有菜单栏菜单项)发送命令?

How to send a menubar app (with no menubar menu items) a command in AppleScript?

我想用 AppleScript 命令控制应用程序 (Shady.app)。不幸的是,它没有标准的菜单栏项目,例如文件、编辑、视图等。

我的目标是通过 AppleScript 以某种方式向应用程序发出命令,以便它切换 "Turn Shady On" & "Turn Shady Off" 命令:

注意:"Turn Shady On"为OFF状态,当Shady处于ON状态时变为"Turn Shady Off"。

如何创建一个脚本,根据它在 AppleScript 中的当前状态来切换这两个方向?还是有比 AppleScript 更好的方式来以编程方式控制它?

通过快捷方式发送命令的标准方法是:

System Preferences > Keyboard > Shortcuts > App Shortcuts

单击 + 和 select Shady,然后您就可以定义要使用的快捷方式。请记住,您需要先使用 + Tab 切换到 Shady,然后再使用快捷方式。

如果您使用像 FastScripts 这样的应用程序,那么您可以创建一个全局快捷方式,而不必先切换到该应用程序,如果该应用程序没有焦点,这有时会更好。

此 AppleScript 将 "Turn Shady Off"

tell application "System Events"
    try
        click menu item "Turn Shady Off" of menu 1 of menu bar item "Shade" of menu bar 1 of application process "Shady"
        click menu bar item 1 of menu bar 2 of application process "Shady"
    end try
end tell

此 AppleScript 将 "Turn Shady On"

tell application "System Events"
    try
        click menu item "Turn Shady On" of menu 1 of menu bar item "Shade" of menu bar 1 of application process "Shady"
        click menu bar item 1 of menu bar 2 of application process "Shady"
    end try
end tell

假设它在状态栏中 运行。

这将打开和关闭

on toggle()
    tell application "System Events"
        try
            click menu item "Turn Shady On" of menu 1 of menu bar item "Shade" of menu bar 1 of application process "Shady"
        end try
        try
            click menu item "Turn Shady off" of menu 1 of menu bar item "Shade" of menu bar 1 of application process "Shady"
        end try
        click menu bar item 1 of menu bar 2 of application process "Shady"
    end tell
end toggle

toggle()

将其保存为 ScriptEditor 中的应用程序或 Automator 中的服务或您选择的任何内容。不需要 FastScripts。

您可以通过 Keyboard Maestro 完成类似的操作。这是一张图片,展示了您想要的效果:

郑重声明,我还认为这太棒了,所以我还提供了一种创建 darken/lighten 全局快捷方式的方法:

您还必须在系统偏好设置中打开“显示 Dock 图标”才能正常工作!

有关详细信息,请参阅论坛上的 this post。为了方便起见,我将继续将其粘贴在这里,并规避 link rot:


sonicly:

I have an application that runs only as a menubar app. It has a simple command that is essentially "Turn App On"/"Turn App Off". Is there a way to make Keyboard Maestro set up a global hotkey to initiate the command in this app?

我只是 运行 讨论了解决您问题的这个主题:

我不知道你是不是OP,我也没有测试建议的解决方案。但也许它至少能让你入门。

sonicly:

So I can enable it to show up on the Dock and with that I was able to set keyboard shortcuts that work... But I have to get focus on the app first (i.e., cmd-tab). That's a hassle and I'd rather just issue something like command-option-shift-space to turn it on and then to toggle it back off again. That seems doable with KM, but I'm not sure how to make the Maestro do that per se

这在KM中很容易,只需使用

另一种选择是使用 Select or Show a Menu Item action (KM Wiki),但我不确定它是否适用于这种情况。