0

I have a code that sends a string as keyboard presses. Sometimes it doesn't seem to work. Application gets only second half of the keyboard presses.

Does anybody know how to add a delay between sending keyboard presses?

code:

procedure SendKeys(const S: String);
var
  InputEvents: PInput;
  I, J: Integer;
begin
  if S = '' then Exit;
  GetMem(InputEvents, SizeOf(TInput) * (Length(S) * 2));
  try
    J := 0;
    for I := 1 to Length(S) do
    begin
      InputEvents[J].Itype := INPUT_KEYBOARD;
      InputEvents[J].ki.wVk := 0;
      InputEvents[J].ki.wScan := Ord(S[I]);
      InputEvents[J].ki.dwFlags := KEYEVENTF_UNICODE;
      InputEvents[J].ki.time := 0;
      InputEvents[J].ki.dwExtraInfo := 0;
      Inc(J);
      InputEvents[J].Itype := INPUT_KEYBOARD;
      InputEvents[J].ki.wVk := 0;
      InputEvents[J].ki.wScan := Ord(S[I]);
      InputEvents[J].ki.dwFlags := KEYEVENTF_UNICODE or KEYEVENTF_KEYUP;
      InputEvents[J].ki.time := 0;
      InputEvents[J].ki.dwExtraInfo := 0;
      Inc(J);
    end;
    SendInput(J, InputEvents[0], SizeOf(TInput));
  finally
    FreeMem(InputEvents);
  end;
end;
mixibixi
  • 13
  • 3
  • How have you diagnosed that delaying is the solution? – David Heffernan Dec 16 '18 at 08:44
  • It's my guess. I usually use this to type passwords over RDP. Noticed it happening when the connection is slow. So I thought delaying key presses might be the solution. – mixibixi Dec 16 '18 at 09:04
  • Doesn't sound like delaying will help. Delaying is really simple though. Call your SendKeys function one character at a time and add a delay between calls. But that won't do you any good. You'll need to find the real source of your problem to make progress. Guesswork is very unlikely to prove effective. – David Heffernan Dec 16 '18 at 10:03
  • 1
    From [the docs](https://learn.microsoft.com/en-us/windows/desktop/api/winuser/ns-winuser-tagkeybdinput) `KEYEVENTF_UNICODE` can only be used together with `KEYEVENTF_KEYUP`, so the first of the two inputs you insert seems to be invalid.. – GolezTrol Dec 16 '18 at 13:08
  • 2
    @Golez - KEYEVENTF_UNICODE can be used by itself (which would mean a key down). The documentation says the flag cannot be combined with anything other than KEYEVENTF_KEYUP. – Sertac Akyuz Dec 17 '18 at 15:33
  • @SertacAkyuz You're right. Thanks! – GolezTrol Dec 17 '18 at 22:06
  • @mixibixi Also note that `KEYEVENTF_UNICODE` takes UTF-16 codeunits as input. If the string contains any Unicode characters that are outside the BMP and thus use surrogate pairs, you must send separate down+up events for each surrogate, but more importantly the two down events must be sent before then sending the two up events. I've posted examples of that in past questions, such as [this one](https://stackoverflow.com/a/50420607/65863) (seems you copied code from [an even earlier answer](https://stackoverflow.com/a/19696146/65863) that predates that one). – Remy Lebeau Dec 17 '18 at 23:58

0 Answers0