LeEnno
LeEnno

Reputation: 328

Clicking an applications menu bar item with AppleScript

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?

Upvotes: 2

Views: 4450

Answers (2)

Lri
Lri

Reputation: 27603

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:

Upvotes: 2

Michele Percich
Michele Percich

Reputation: 1892

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.

Upvotes: 1

Related Questions