Skip to content

Instantly share code, notes, and snippets.

@knugie
Forked from efi/keyboard_controller.rb
Last active March 10, 2022 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save knugie/2813385512f61787c5c4097914bae746 to your computer and use it in GitHub Desktop.
Save knugie/2813385512f61787c5c4097914bae746 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