我在主应用程序中捕获转义键遇到了一个奇怪的问题。我创建了一个简单的测试表单来查看可能出现的问题,因为按下转义键之前已经工作了。到目前为止,它仍然没有工作,我不确定为什么。
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 - 所有其他键都在此处中断。我测试了我的键盘只是为了确保键正常运行并且它很好。
是否有可能导致这种情况或我做错的事情?
感谢。
答案 0 :(得分:0)
将其添加到组件的类中:
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;
答案 1 :(得分:0)
这是因为您将Button1的Cancel
属性设置为True
。评论这一行:
button1.Cancel := True;
您将能够捕获Escape键。这些都是独一无二的。
答案 2 :(得分:0)
首先尝试重新启动。它解决了这个问题。