当另一个控件具有焦点时,窗体如何检测KeyDown事件? [英] How can my form detect KeyDown events when another control has the focus?

查看:73
本文介绍了当另一个控件具有焦点时,窗体如何检测KeyDown事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;

只有将焦点设置为主窗体"时,以上事件才起作用. 如果我运行该应用程序并继续按Tab键,然后将Focus更改为Form上的任何控件,它将禁用此事件,直到我们再次将Focus更改为主窗体为止.

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 ?

问题是 即使Focus不在主要形式下,我如何检测到三个键也被按下?

我还想如果我使用 RegisterHotKey ,但是在我的应用程序运行时注册 Q,W和E 不是一个好主意.

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;

推荐答案

您可以设置

You can set KeyPreview of the form to true.

如果KeyPreview为true,则键盘事件会在它们之前在窗体上发生 出现在活动控件上. (活动控件由 ActiveControl属性.)

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.)

如果KeyPreview为false,则仅在活动键盘上发生键盘事件 控制.

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

导航键(Tab,BackTab,箭头键等)是 不受KeyPreview的影响,因为它们不会生成键盘 事件.同样,当按钮具有焦点或当其默认值时 属性为true,则Enter键不受KeyPreview的影响,因为 它不会生成键盘事件.

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默认为假.

这篇关于当另一个控件具有焦点时,窗体如何检测KeyDown事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆