Search code examples
rubywindowskeystrokes

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-C on the file and copy the information, is this possible in a Ruby program, without the use of external gems?

Operating system: Windows 7


Solution

  • 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. 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.

    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`