windows - Delphi XE 和使用 OnKeyDown 捕获箭头键

标签 windows delphi winapi delphi-xe

我希望我的表单能够处理箭头键,而且我可以做到——只要表单上没有按钮。这是为什么?

最佳答案

关键消息由接收这些消息的控件本身处理,这就是为什么当您在按钮上时表单没有收到消息。所以通常你必须对这些控件进行子类化,但 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 原始问题,您需要以某种方式调用 onKeyDown 以便他的事件代码起作用(随意编辑;评论太长)。

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_UP, VK_RIGHT, 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;

关于windows - Delphi XE 和使用 OnKeyDown 捕获箭头键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8620703/

相关文章:

windows - 在 Windows 中的 XAMPP 上安装 Zend Framework 2

c# - 处理器使用情况(强制完全使用)

node.js - Cypress 无法在 Windows 上启动

Delphi Firemonkey 2 .color 属性

delphi - 在Delphi中查找 "non-leak"内存使用问题的策略或工具?

c++ - 如何使用 RegLoadKey 函数从默认用户加载 NTUSER.DAT 文件?

c# - 无法将 IStorageItem 转换为 StorageFile

Delphi 2007 - 允许在 TSaveDialog 中选择只读文件

c - 使用缓冲区的 Windows AlphaBlend

winapi - 我可以确定哪个进程向我的窗口发送了消息吗?