I wouldn't recommend using
SendMessage since then you'd have to deal with the nitty-gritty (platform-dependent) details of how messages are encoded.
The simplest way is to just call the event handler directly:
procedure SimulateKeyPress(Memo: TMemo);
var
Key: Word = VK_W;
begin
Memo.OnKey(Nil, Key, []); // Sends 'W' without any modifiers
end;
There exist other possibilities too; some wait for the event to complete, others just place it into the message queue and return immediately:
UnitFoo.pasunit UnitFoo;
{$mode objfpc}{$H+}
interface
uses
Classes, Forms, StdCtrls, LMessages;
type
TFormFoo = class(TForm)
MemoBar: TMemo;
procedure AsyncMemoKey(Data: PtrInt);
procedure MemoBarKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
end;
var
FormFoo: TFooForm;
procedure SimulateMemoBarEvent();
implementation
procedure SimulateMemoBarEvent();
var
Key: Word = VK_W;
begin
// Option 1: Direct call
FormFoo.MemoBarKeyDown(Nil, Key, []);
// Option 2: Indirect call
FormFoo.MemoBar.OnKeyDown(Nil, Key, []);
// Option 3: Synchronous message
SendMessage(FormFoo.MemoBar.Handle, LM_KEYDOWN, Key, $00000000);
// Option 4: Asynchronous message
PostMessage(FormFoo.MemoBar.Handle, LM_KEYDOWN, Key, $00000000);
// Option 5: Asynchronous event
Application.QueueAsyncCall(@FormFoo.AsyncMemoKey, Key);
end;
procedure TFormFoo.AsyncMemoKey(Data: PtrInt);
var
Key: Word;
begin
Key := Data;
// Any of options 1-4, e.g. option 1
MemoBar.OnKeyDown(Nil, Key, []);
end;
procedure TFormFoo.MemoBarKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
// ...
end;
end.
UnitFoo.lfm:object FormFoo: TFormFoo
object MemoBar: TMemo
OnKeyDown = MemoBarKeyDown
end
end