简体   繁体   English

从程序中运行击键

[英]Running keystrokes from program

I'm writing a program to automate an e-mail process and would like to know if there's a way to run keystrokes from within the program? 我正在编写一个用于自动执行电子邮件过程的程序,并且想知道是否有一种方法可以在程序内运行击键?

For example say I have this string: 例如说我有这个字符串:

str = "test"

And it gets copied to a file: 并将其复制到文件中:

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

And after that I want to use CNTRL-A ; 之后,我想使用CNTRL-A CNTRL-C on the file and copy the information, is this possible in a Ruby program, without the use of external gems? CNTRL-C上的文件并复制信息,这是否可能在Ruby程序中而不使用外部gems?

Operating system: Windows 7 作业系统:Windows 7

If you can't install gems but can copy ClipText.exe to your current directory, do so then run this code in Ruby: 如果您无法安装gems,但可以将ClipText.exe复制到当前目录,请执行以下操作,然后在Ruby中运行以下代码:

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

For a more rigorous way of executing commands on Windows see " How to execute Windows CLI commands in Ruby? ". 有关在Windows上执行命令的更严格的方法,请参阅“ 如何在Ruby中执行Windows CLI命令? ”。

If sending arbitrary keystrokes to other applications is what you're after you can use the gem https://github.com/erinata/auto_click for it. 如果要向其他应用程序发送任意击键,您可以使用gem https://github.com/erinata/auto_click However, if you can't use gems, what you can do instead is run NirCmd (or one of its alternatives ) with the appropriate command line arguments to achieve the same result. 但是,如果您不能使用的宝石,你可以做什么,而不是运行的NirCmd (或者一个它的 替代品 ),使用适当的命令行参数来达到同样的效果。

For example: 例如:

# 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`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM