Clicking an applications menu bar item with AppleScript

老子叫甜甜 提交于 2019-12-10 11:05:35

问题


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.

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

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.

Any suggestions?


回答1:


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

Related questions:

  • Applescript: on clicking Menu Bar item via gui script
  • Is AppleScript UI Scripting very slow in general, or is it my script, or something else?



回答2:


Actually, the key code for the down arrow seems to be 125. Try this:

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

There is a short delay (a couple of seconds) after the click menu bar... command, I don't know why.



来源:https://stackoverflow.com/questions/16663846/clicking-an-applications-menu-bar-item-with-applescript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!