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:

code format="bb4w" 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 code You could for example send an entire string by calling the procedure for each character:

code format="bb4w" test$ = "Hello World!" + CHR$13 FOR I% = 1 TO LEN(test$) PROCfake(ASC MID$(test$ ,I%)) NEXT code 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.