Skip to content

Instantly share code, notes, and snippets.

@efi
Created April 5, 2015 16:49
Show Gist options
  • Save efi/ecd4742de203a4c724be to your computer and use it in GitHub Desktop.
Save efi/ecd4742de203a4c724be to your computer and use it in GitHub Desktop.
Send system keyboard events in JRuby via java.awt.Robot
class KeyboardController
def initialize
@robot = java.awt.Robot.new
end
def type *args
[args].flatten.map(&:to_s).map{|s|s.split(/\s+/)}.flatten.map(&:upcase).each do |n|
press, name = (n[0]=="-") ? [false,n[1..-1]] : [true,n]
press ? @robot.key_press(@code) : @robot.key_release(@code) if @code = java.awt.event.KeyEvent.const_get("VK_#{name}")
end
self
end
end
kc = KeyboardController.new
kc.type(%w[a b c d shift e f -shift g h]); kc.type("i","j"); kc.type(:k,"L M"); kc.type(:"N SHIFT O P -SHIFT Q r s")
# types: => abcdEFghijklmnOPqrs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment