Search code examples
delphisendinputmemo

SendInput showing data sent out of sequence


I am experimenting with SendInput by sending strings to a memo. I mix the SendInput commands with calls to Memo.Lines.Add('....'). To my surprise all the Memo.Lines.Add commands execute before any of the SendInput routines. Why? How can I get the memo to display the information in the correct order?

My code looks like this:

procedure TForm1.Button1Click(Sender: TObject);
const
  AStr = '123 !@# 890 *() abc ABC';
var
  i: integer;
  KeyInputs: array of TInput;

  procedure KeybdInput(VKey: Byte; Flags: DWORD);
  begin
    SetLength(KeyInputs, Length(KeyInputs)+1);
    KeyInputs[high(KeyInputs)].Itype := INPUT_KEYBOARD;
    with  KeyInputs[high(KeyInputs)].ki do
    begin
      wVk := VKey;
      wScan := MapVirtualKey(wVk, 0);
      dwFlags := Flags;
    end;
  end;

begin
  Memo1.SetFocus;
  Memo1.Lines.Add('AStr := ' + AStr);

  Memo1.Lines.Add('');
  Memo1.Lines.Add('Use:   KeybdInput(ord(AStr[i]),0)');
  SetLength(KeyInputs,0);
  for i := 1 to Length(AStr) do KeybdInput(ord(AStr[i]),0);
  SendInput(Length(KeyInputs), KeyInputs[0], SizeOf(KeyInputs[0]));

  Memo1.Lines.Add('');
  Memo1.Lines.Add('Use:   KeybdInput(vkKeyScan(AStr[i]),0)');
  SetLength(KeyInputs,0);
  for i := 1 to Length(AStr) do KeybdInput(vkKeyScan(AStr[i]),0);
  SendInput(Length(KeyInputs), KeyInputs[0], SizeOf(KeyInputs[0]));
end;

And I expected the result to look like this:

But it actually looks like this:


Solution

  • The keyboard inputs that you send with SendInput goes through the Windows messaging system and end up in your applications message queue. The message queue is not processed before you exit from Button1Click().

    When something gets added to a queue, it takes time for it to come out the front of the queue

    To see the events in the order you are expecting, you would need to insert calls to Application.Processmessages() after each SendInput(). Calling Application.ProcessMessages() is not generally advisable, though:

    The Dark Side of Application.ProcessMessages in Delphi Applications