Delphi 自定义按钮加速键

Delphi custom button accel key

我正在编写一个派生自 tExCustomControl 的自定义按钮,而后者又派生自 tCustomControl。 tExCustomControl 组件负责绘制和显示标题。我设法使用 WinAPI 显示带有加下划线的 accel 字符的标题。我怎么知道 Windows accel 键与 tExButton 相关联,所以它可以处理事件?

你什么都没告诉 Windows。当用户键入加速器时,Windows 会向您的应用程序发送一条 WM_SYSCHAR 消息,VCL 会自动处理该消息。当 VCL 搜索哪个控件处理加速器时,您的组件将收到一条 CM_DIALOGCHAR 消息,您需要响应该消息,例如:

type
  TMyCustomButton = class(tExCustomControl)
  private
    procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
  end;

procedure TMyCustomButton.CMDialogChar(var Message: TCMDialogChar);
begin
  if IsAccel(Message.CharCode, Caption) and Enabled and Visible and
    (Parent <> nil) and Parent.Showing then
  begin
    Click;
    Result := 1;
  end else
    inherited;
end;

IsAccel()Vcl.Forms单元中的public函数:

function IsAccel(VK: Word; const Str: string): Boolean;

它从提供的 Str 值解析加速器并将其与提供的 VK 值进行比较。

上面的代码正是 TSpeedButton 实现加速器的方式。