How does my form detect KeyDown events when another control has focus?
procedure TMainForm.KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (GetKeyState(Ord('Q'))<0) and (GetKeyState(Ord('W'))<0) and (GetKeyState(Ord('E'))<0)
then ShowMessage('You pressed it');
end;
the above event only works if the focus is on the main form. if i launch the app and keep pressing Tab and change Focus to any form element, will it disable this event until we focus again on the main form?
Question: How can I detect that three keys are pressed even if the focus is not on the main form?
Also I thought that if I use RegisterHotKey but it is not recommended to register Q, W and E while my application is running.
procedure TMainForm.WMHotKey(var Msg: TWMHotKey);
begin
if ActiveCaption = 'my Form Caption' then
Begin
if Msg.HotKey = HotKey1 then
begin
//DoSomething;
end
else
if Msg.HotKey = HotKey2 then
begin
//DoSomething;
end;
End
else
//DoSomething;
end;
source to share
You can set KeyPreview
forms to true.
If
KeyPreview
true, keyboard events appear on the form before they occur on active control. (Active control is defined by the ActiveControl Property.)If
KeyPreview
false, keyboard events only occur when monitoring is active.Navigation keys (Tab, BackTab, arrow keys, etc.) are unaffected
KeyPreview
because they do not generate the Events keyboard. Likewise, when a button has focus, or when its default property is true, the Enter key is unaffectedKeyPreview
because it does not generate keyboard events.
KeyPreview
default false.
source to share