User Tools

Site Tools


faking_20keyboard_20input

Faking keyboard input

by Richard Russell, September 2007

In special circumstances you may wish to 'automate' another application, that is to control it from your BASIC program rather then via user input (e.g. from the keyboard). Ideally you would do that through an official 'COM automation' interface, such as is provided by several Microsoft applications; the main BBC BASIC for Windows documentation describes how to do that.

However relatively few applications provide such an automation interface, and in its absence you might have to resort to 'faking' keyboard input, that is to generate what appear to be keypresses without actually needing to press any keys on the keyboard. Although this is relatively straightforward to achieve it's not ideal, because it's difficult to guarantee that the application to which you want to send the input currently has the input focus, and to ensure that the entry point (text cursor or whatever) is where you want it to be. Sending 'faked' input to the wrong application or to the wrong input field can cause considerable confusion, if not worse!

Nevertheless it can occasionally be a useful technique. The procedure listed below takes as a parameter a normal ASCII code (which may be that of a 'printing' character or a control code like Tab) and generates input as if the appropriate key(s) had been pressed on the keyboard:

        DEF PROCfake(C%) : LOCAL V%
        SYS "VkKeyScan", C% TO V%
        IF V% AND &100 SYS "keybd_event", 16, 0, 0, 0
        IF V% AND &200 SYS "keybd_event", 17, 0, 0, 0
        IF V% AND &400 SYS "keybd_event", 18, 0, 0, 0
        SYS "keybd_event", V% AND &FF, 0, 0, 0
        SYS "keybd_event", V% AND &FF, 0, 2, 0
        IF V% AND &400 SYS "keybd_event", 18, 0, 2, 0
        IF V% AND &200 SYS "keybd_event", 17, 0, 2, 0
        IF V% AND &100 SYS "keybd_event", 16, 0, 2, 0
        ENDPROC

You could for example send an entire string by calling the procedure for each character:

        test$ = "Hello World!" + CHR$13
        FOR I% = 1 TO LEN(test$)
          PROCfake(ASC MID$(test$ ,I%))
        NEXT

Note that the above code assumes that when it is run none of the 'shift' or 'control' keys are currently pressed. If they might be, the code would have to be enhanced to cope with that situation.

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
faking_20keyboard_20input.txt · Last modified: 2024/01/05 00:22 by 127.0.0.1