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.

Stefan
  • 109,145
  • 14
  • 143
  • 218
Chirantan
  • 15,304
  • 8
  • 49
  • 75

1 Answers1

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

Community
  • 1
  • 1
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
  • The [applescript keycodes](http://eastmanreference.com/complete-list-of-applescript-key-codes/) can be found at the link provided :) – mbigras Feb 20 '17 at 07:51