Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send keyboard and mouse commands to the underlying operating system using Ruby?

Is there an operating system neutral way for Ruby to send keyboard and mouse events to the underlying operating system?

One obvious (to me) approach is to use the Ruby/Java bindings and use java.awt.Robot, but that just seems silly.

like image 612
John Avatar asked Feb 04 '23 09:02

John


2 Answers

For Mac:

gem install rb-appscript

Then you can test it with a script like this:

require "rubygems"
require "appscript"
include Appscript

app("TextEdit").activate
app("System Events").keystroke("Look Ma, keystrokes!")

For Windows: (untested, borrowed from this thread)

require "win32ole"

wsh = WIN32OLE.new("WScript.Shell")
wsh.Run("Notepad.exe")
while not wsh.AppActivate("Notepad")
  sleep .1
end
wsh.SendKeys("Look Ma, keystrokes!")
like image 83
Ryan McGeary Avatar answered Mar 05 '23 17:03

Ryan McGeary


For completeness sake, I thought I would include a solution for if you're using Linux.

On Linux, for automating keystrokes you can use xdotool. There also a gem for Ruby, but it's not really required considering that send keystrokes is a easy as:

%x(xdotool key super+w) #this would press the keys super and w simultaneoulsy

There's also mouse events too.

like image 29
Seanny123 Avatar answered Mar 05 '23 19:03

Seanny123