How can my form detect KeyDown events when another control has the focus?

与世无争的帅哥 提交于 2021-02-04 15:43:08

问题


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;

回答1:


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.



来源:https://stackoverflow.com/questions/26761084/how-can-my-form-detect-keydown-events-when-another-control-has-the-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!