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

Joh*_*ohn 8 ruby keyboard mouseevent

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

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

Rya*_*ary 7

对于Mac:

gem install rb-appscript
Run Code Online (Sandbox Code Playgroud)

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

require "rubygems"
require "appscript"
include Appscript

app("TextEdit").activate
app("System Events").keystroke("Look Ma, keystrokes!")
Run Code Online (Sandbox Code Playgroud)

对于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!")
Run Code Online (Sandbox Code Playgroud)


Sea*_*123 5

为了完整起见,我想如果您使用 Linux,我会包含一个解决方案。

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

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

还有鼠标事件。