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

我与影子孤独终老i 提交于 2019-12-10 12:52:54

问题


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.


回答1:


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!")



回答2:


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.




回答3:


Unfortunatly, rb-applescript is a little dated and wonky.

For the mac, you may want to use:

%x(osascript -e 'tell application "System Events" to keystroke "Look Ma, keystrokes!"')


来源:https://stackoverflow.com/questions/1446327/how-to-send-keyboard-and-mouse-commands-to-the-underlying-operating-system-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!