我在主应用程序中遇到了一个奇怪的问题,即捕获转义键。我创建了一个简单的测试表单来查看可能出现的问题,因为按escape键之前是工作的。到目前为止,它仍然不能工作,我不知道为什么。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure Button2KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
procedure OnAppMessage(var Msg: TMsg; var Handled: Boolean);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.OnAppMessage(var Msg: TMsg; var Handled: Boolean);
begin
if Msg.message = WM_KeyDown then
showmessage('MSG');
end;
procedure TForm1.Button1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = VK_ESCAPE then
showmessage('ESC');
end;
procedure TForm1.Button2KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = VK_ESCAPE then
showmessage('ESC');
end;
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = vk_escape then
Button1Click(sender);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
showmessage('Button1Click');
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Application.OnMessage := OnAppMessage;
button1.Cancel := True; // set at design time as well
self.KeyPreview := True; // set at design time as well
end;
end.
由于某些原因,当按escape时,它不会在我在button1中放置的点上断开。OnKeyDown或甚至应用程序消息WM_KEYDOWN——所有其他键在这里断开。我测试了我的键盘,只是为了确保这个键能正常工作,而且很好。
是否有什么可能导致这个或我做错了?
谢谢。
将此添加到组件的类中:
procedure HandleDlgCode(var Msg:TMessage); message WM_GETDLGCODE;
,然后在实现部分:
procedure TComponentClass.HandleDlgCode(var Msg:TMessage);
var
M: PMsg;
begin
Msg.Result := DLGC_WANTALLKEYS or DLGC_WANTESCAPE or DLGC_WANTCHARS or DLGC_HASSETSEL;
if Msg.lParam <> 0 then
begin
M := PMsg(Msg.lParam);
case M.message of
WM_KEYESCAPE, WM_CHAR:
begin
Perform(M.message, M.wParam, M.lParam);
Msg.Result := Msg.Result or DLGC_WANTMESSAGE;
end;
end;
end
else
Msg.Result := Msg
end;
这是因为您将Button1的Cancel
属性设置为True
。注释行:
button1.Cancel := True;
,您将能够捕获转义键。
尝试重新启动。