我想要我的窗体处理箭头键,我可以做 – 只要表单上没有按钮.为什么是这样?
解决方法
主要消息由收到这些消息的控件本身处理,这就是为什么当您在表单上没有收到消息的按钮时.所以通常你必须对这些控件进行子类化,但是,如果表单感兴趣,则VCL很适合请求父母表单做什么:
type TForm1 = class(TForm) .. private procedure DialogKey(var Msg: TWMKey); message CM_DIALOGKEY; .. procedure TForm1.DialogKey(var Msg: TWMKey); begin if not (Msg.CharCode in [VK_DOWN,VK_UP,VK_RIGHT,VK_LEFT]) then inherited; end;
François编辑:要回答OP原始问题,您需要以某种方式调用KeyDown,以便他的事件代码可以工作(可以自由编辑;对于注释来说太长了).
type TForm1 = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } procedure DialogKey(var Msg: TWMKey); message CM_DIALOGKEY; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.DialogKey(var Msg: TWMKey); begin case Msg.CharCode of VK_DOWN,VK_LEFT: if Assigned(onKeyDown) then onKeyDown(Self,Msg.CharCode,KeyDataToShiftState(Msg.KeyData)); else inherited end; end; procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_DOWN: Top := Top + 5; VK_UP: Top := Top - 5; VK_LEFT: Left := Left - 5; VK_RIGHT: Left := Left + 5; end; end;