如何使用Ruby向底层操作系统发送键盘和鼠标命令?
-
22-07-2019 - |
题
Ruby 是否有一种与操作系统无关的方式将键盘和鼠标事件发送到底层操作系统?
一种明显的(对我来说)方法是使用 Ruby/Java 绑定并使用 java.awt.Robot,但这看起来很愚蠢。
解决方案
对于苹果机:
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宝石,但它不是真正需要考虑到发送击键是容易的:
%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!"')
不隶属于 StackOverflow