2

I want to trigger certain key-presses like enter, esc and arrow keys. I've googled and am surprised to not be able to find the solution.

EDIT

More specifically, I want to trigger some global keyboard shortcuts through ruby script.

5
  • 3
    Key events in a terminal, a browser, a desktop window? Commented Sep 9, 2014 at 11:54
  • Could you define "global"? :-) Commented Sep 9, 2014 at 12:04
  • Global OS level shortcuts. OSX. Commented Sep 9, 2014 at 12:04
  • There's a gem called AXElements, see stackoverflow.com/a/25382115/477037 Commented Sep 9, 2014 at 12:07
  • Thanks Stefan, trying it out. Running into some errors but fighting them. Also trying the answer below by p11y. Commented Sep 9, 2014 at 12:39

1 Answer 1

2

On OS X, you can use AppleScript to do that. Here's an example that performs the keyboard shortcut cmd + alt + ctrl + W

tell application "System Events" 
  keystroke "w" using {control down, option down, command down}
end tell

For the arrow keys, use key code instead of keystroke:

# Key codes for arrow keys:
# 
# LEFT  123
# RIGHT 124
# UP    126
# DOWN  125

tell application "System Events" 
  key code 123 using {control down, option down, command down}
end tell

You can invoke AppleScript from Ruby by shelling out to osascript:

def osascript(script)
  system 'osascript', *script.split(/\n/).map { |line| ['-e', line] }.flatten
end

osascript <<-END
  tell application "System Events" 
    keystroke "w" using {control down, option down, command down}
  end tell
END

Sources

Sign up to request clarification or add additional context in comments.

1 Comment

The applescript keycodes can be found at the link provided :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.