Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can my form detect KeyDown events when another control has the 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 work if the Focus set to the Main Form. if i run the application and keep pressing Tab and changing the Focus to any control on the Form it will disable this event until we change the Focus again to the main form ?

the Question is how i can detect the three keys are pressed even if the Focus not in the main form ?

also i thought if i use RegisterHotKey but is not good idea 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;
like image 369
RepeatUntil Avatar asked Nov 05 '14 15:11

RepeatUntil


1 Answers

You can set KeyPreview of the form to true.

If KeyPreview is true, keyboard events occur on the form before they occur on the active control. (The active control is specified by the ActiveControl property.)

If KeyPreview is false, keyboard events occur only on the active control.

Navigation keys (Tab, BackTab, the arrow keys, and so on) are unaffected by KeyPreview because they do not generate keyboard events. Similarly, when a button has focus or when its Default property is true, the Enter key is unaffected by KeyPreview because it does not generate a keyboard events.

KeyPreview is false by default.

like image 200
Sertac Akyuz Avatar answered Sep 29 '22 09:09

Sertac Akyuz