工具栏中的主菜单未按预期工作

Main Menu in toolbar not working as expected

我创建了一个 VCL 表单应用程序,添加了一个主菜单并从菜单模板中插入 "MDI Frame Menu"。我运行程序和使用加速键。一切都按预期工作。

我现在添加一个工具栏,断开主菜单与窗体的连接,然后 link 它到工具栏。我运行程序。现在,只需按相应的键而不按 Alt 即可激活菜单项(例如,按 "W" 打开 Windows 菜单项。 如何让工具栏上的菜单在没有它的情况下像主菜单一样运行?

我为我的问题创建了一个答案(可能有更简单和更优雅的答案)。使工具栏中的 TMainMenu 与窗体上的 TMainMenu 行为相同的步骤是:

  • 在 MainForm 上放置一个 TMainMenu
  • 根据需要填充 MainMenu
  • 在表单上放置一个 ActionList
  • 确保所有菜单项都通过 ActionList 执行
  • 清除 MainForm
  • 的菜单 属性
  • 在窗体上放置一个 TToolbar
  • 将 MainMenu 分配给工具栏
  • 编写程序DeleteHotKeysOfToolbarMenu(Sender: TObject); (见下面的代码片段)
  • 为 ActionList.OnExecute 事件编写代码,如下所示
  • 将 MainForm 的 KeyPreview 属性 设置为 true
  • 编写MainForm.OnKeyPress事件如下图
  • 在 MainForm 的 Create 过程中调用 DeleteHotKeysOfToolbarMenu 以在没有任何可见热键的情况下启动程序
  • 就是这样

以下是代码片段:

procedure TMainForm.DeleteHotKeysOfToolbarMenu(Sender: TObject);
var
   m: integer;
begin
   for m := 0 to Toolbar.ButtonCount-1 do
     Toolbar.Buttons[m].Caption := StripHotKey(Toolbar.Buttons[m].Caption);
end;

procedure TMainForm.ActionListExecute(Action: TBasicAction; var Handled: Boolean);
begin
   if Action.ActionComponent.ClassType = TMenuItem then
   DeleteHotKeysOfToolbarMenu(Self);
end;

TMainForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
   if (ssAlt in Shift) or (Key = VK_F10) then
   begin
     Toolbar.Menu := nil;
    Toolbar.Menu := MainMenu;
  end;
  if Key = VK_Escape then DeleteHotKeysOfToolbarMenu(Self);
end;