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