使用 AppleScript 单击应用程序菜单栏项

使用 AppleScript 单击应用程序菜单栏项

问题描述:

我使用 Mac 版时间跟踪器作为我的时间跟踪器.它有一个菜单栏项,我希望能够通过键盘快捷键访问.

I use Time Tracker For Mac as my, well, time tracker. It has a menu bar item which I want to be able to access via keyboard shortcut.

我找到了一种使用 GUI 脚本单击项目的方法:

I found a way to click the item with GUI scripting:

tell application "System Events" to tell process "Time Tracker"
    click menu bar item of menu bar 2
end tell

不幸的是,除非我在菜单上操作(即按 Enter 或 Esc 键),否则脚本不会返回成功.所以如果我想触发向下箭头键...

Unfortunately the script does not return success unless I acted on the menu (i.e. pressing Enter or Esc key). So if I want to trigger the down arrow key...

tell application "System Events" to tell process "Time Tracker"
    click menu bar item of menu bar 2
    -- hangs here forever until menu is closed
    tell application "System Events" to key code 124
end tell

脚本只是永远等待.如果我点击退出,菜单栏项目将关闭,然后才会触发向下箭头键.

the script just waits forever. If I hit escape the menu bar item closes and only then the down arrow key will be triggered.

有点奇怪.我只需要点击菜单栏项阻止进一步的脚本执行.

It's kind weird. I just need the menu bar item's click to not block further script execution.

有什么建议吗?

对我来说,大约 5 秒后单击命令返回.一种解决方法是使用忽略应用程序响应并终止系统事件:

The click command returns after about 5 seconds for me. One workaround is to use ignoring application responses and terminate System Events:

ignoring application responses
    tell application "System Events" to tell process "Time Tracker"
        click menu bar item 1 of menu bar 2
    end tell
end ignoring
do shell script "killall System\\ Events"
delay 0.1
tell application "System Events" to tell process "Time Tracker"
    tell menu bar item 1 of menu bar 2
        click menu item 2 of menu 1
    end tell
end tell

相关问题: