Search code examples
windowsperlkeystroke

Imitate pressing keyboard F-keys using a Perl script


Is there a way that I can imitate the pressing of a function key (F1-F12) from a Perl script on Windows 7?

I have a program that requires F7 to be pressed in order to stop it.

I have tried killing the program process, but that doesn't stop the process cleanly.


Solution

  • If you're on Windows, Win32::GuiTest can do what you want. They have several examples of using SendKeys to press function keys.

    On Unix the situation is both easier and harder. Function keys are usually mapped in a terminal to send several characters. You can find out what they are using ord and sprintf to get their hex values (easier to work with). Here's an example of "kj" as a simple example, then F1 through F7.

    $ perl -wle 'while(<>) { chomp; print join ", ", map { sprintf "%x", ord } split //, $_ }'
    kj
    6b, 6a
    ^[OP
    1b, 4f, 50
    ^[OQ
    1b, 4f, 51
    ^[OR
    1b, 4f, 52
    ^[OS
    1b, 4f, 53
    ^[[15~
    1b, 5b, 31, 35, 7e
    ^[[17~
    1b, 5b, 31, 37, 7e
    ^[[18~
    1b, 5b, 31, 38, 7e
    ^[[19~
    1b, 5b, 31, 39, 7e
    

    ASCII 1b is the escape character (represented on the terminal by a ^[). 5b is [, and so on. So you can print those strings to the program's input or to the tty. For example, F8 would be "\x{1b}[19~".

    Why are F1-F4 different? The VT100 terminal, upon which this is all based, only had four function keys. The later VT220 added the rest.

    There's probably a module to take care of this for you, but I can't find it.