如何使用Ruby将键盘和鼠标命令发送到底层操作系统?

是否有一种操作系统中立的方式让Ruby将键盘和鼠标事件发送到底层操作系统?

一个显而易见的(对我而言)方法是使用Ruby / Java绑定并使用java.awt.Robot,但这看起来很愚蠢。

对于Mac:

gem install rb-appscript 

然后你可以用这样的脚本测试它:

 require "rubygems" require "appscript" include Appscript app("TextEdit").activate app("System Events").keystroke("Look Ma, keystrokes!") 

对于Windows 🙁未经测试, 借用此线程 )

 require "win32ole" wsh = WIN32OLE.new("WScript.Shell") wsh.Run("Notepad.exe") while not wsh.AppActivate("Notepad") sleep .1 end wsh.SendKeys("Look Ma, keystrokes!") 

为了完整起见,我想如果你使用Linux,我会提供一个解决方案。

在Linux上,为了自动执行键击,您可以使用xdotool。 还有一个Ruby的gem,但考虑到发送击键很简单,它并不是真的需要:

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

还有鼠标事件。

不幸的是, rb-applescript有点陈旧和不稳定。

对于mac,您可能想要使用:

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