运行 程序击键

Running keystrokes from program

我正在编写一个程序来自动执行电子邮件处理,想知道是否有办法从程序中 运行 击键?

例如我有这个字符串:

str = "test"

然后它被复制到一个文件中:

File.open('str.txt', 'w') { |s| s.puts(str }

之后我想使用 CNTRL-ACNTRL-C 在文件上并复制信息,这在 Ruby 程序中是否可行,而不使用外部 gem?

操作系统:Windows7

如果您无法安装 gems 但可以将 ClipText.exe 复制到您的当前目录,请执行 运行 Ruby 中的代码:

File.open('str.txt', 'w') { |s| s.puts(str }
`cliptext.exe from str.txt`

有关在 Windows 上执行命令的更严格的方法,请参阅“How to execute Windows CLI commands in Ruby?”。

如果向其他应用程序发送任意击键是您想要的,您可以使用 gem https://github.com/erinata/auto_click for it. However, if you can't use gems, what you can do instead is run NirCmd (or one of its alternatives) 和适当的命令行参数来获得相同的结果。

例如:

# Tell the OS to bring up the Notepad window and give it the time
# to do so.
`nircmd win activate ititle notepad`
sleep 0.5
# Select all text in the Notepad window and copy it to the
# clipboard.
`nircmd sendkeypress ctrl+a`
`nircmd sendkeypress ctrl+c`