微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

简单的键盘监听测试程序

用delphi时间键盘监听时间;当按下一个键时,在Edit组件中显示按键的名称
测试中遇到的问题,就是按键没反应,解决方法是在窗体的属性中找到 KeyPriview 的属性改为 ture;
具体的说明树下:
Specifies whether the form should receive keyboard events before the active control.


Delphi Syntax:


property KeyPreview: Boolean;


C++ Syntax:


__property bool KeyPreview = {read=FKeyPreview,write=FKeyPreview,stored=IsForm,default=0};


Description


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.
网友解释:
如果把窗体的KeyPreview属性设为True,那么窗体将比其内的控件优先获得键盘事件的激活权。比如窗体Form1和其内的文本框Text1都准备响应KeyPress事件,那么以下代码将首先激活窗体的KeyPress事件:

Private Sub Form_Load()
    Me.KeyPreview = True
End Sub

Private Sub Form_KeyPress(KeyAscii As Integer)
    MsgBox "这是窗体的KeyPress事件"
End Sub

Private Sub Text1_KeyPress(KeyAscii As Integer)
    MsgBox "这是文本框的KeyPress事件"
End Sub


unit Uni_Main;


interface


uses
  Windows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls;


type
  TForm1 = class(TForm)
    lbl_press: TLabel;
    edt_show: TEdit;
    procedure FormKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
  private
    { Private declarations }
  public
    { Public declarations }
  end;


var
  Form1: TForm1;


implementation


{$R *.dfm}
//窗体按键事件测试
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  //按下什么键显示按下了什么键
  case Key of
    VK_ESCAPE: edt_show.Text := '您按下了 ESC 键';
    VK_CONTROL: edt_show.Text := '您按下了 CONTROL 键';
  end;
end;


end.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐