I'm trying to stop a TMemo
(and also TRichEdit
) control from eating Escape
keys.
If the user is focused in a TEdit
, pressing Escape
will trigger the form to do what the form does when the user presses escape. If the user is focused in a TMemo
, pressing escape is eaten by the TMemo
.
Of course i could do the hack:
procedure TForm1.Memo1KeyPress(Sender: TObject; var Key: Char);
begin
if Key = #27 then
begin
//figure out how to send a key to the form
end;
end;
But that is not ideal (i have to handle the escape key, rather than letting the form handle it).
Of course i could do the hack:
Form1.KeyPreview := True;
procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #27 then
begin
//Figure out how to invoke what the form was going to do when the user presses escape
end;
end;
But that is not ideal (i have to handle the escape key, rather than letting the form handle it).
So we'll answer the question rather than the problem
Instead we'll take this opportunity to learn something. How is it that a TMemo
is even receiving a keyPress event associated with the escape key, when a TEdit
doesn't:
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
if Key = #27 then
begin
//never happens
end;
end;
The TEdit
and TMemo
are the same Windows EDIT
common control.
Why does escape bypass the form's KeyPreview
If i turn on the form's KeyPreview
, and the user presses Escape
while focused in a TEdit
box, and a button's Cancel
property is set, the form closes and:
- the
Edit1.KeyPress
event is not triggered - the
Form1.KeyPress
event is not triggered
If an Action is created, whose Shortcut
is Esc
, then no KeyPress
event is raised, no matter what control the user is focused in.
tl;dr: Where is the TMemo.WantEscape
property?
Handled := True
to consume it. Honestly, I find the VCLOnKeyPress
events to have a very weird behaviour (specially if you use form'sKeyPreview
). – GabrielF