delphi - 运行时分配的操作的快捷方式不会在自定义组件中触发

标签 delphi components action hotkeys

当代码完全在运行时创建时(即没有表单设计器组件),我在将 Action 分配给自定义组件的继承 Action 属性时遇到问题。如果我在表单设计器中使用 ActionList,然后使用相同的代码,一切都会正常工作。

这是我从 TCustomControl 派生的组件构造函数:

  self.FButtonSCActionList := TActionList.Create( self.Parent );
  self.FButtonSCActionList.Name := 'ButtonSCActionList';
  self.FButtonSCAction := TAction.Create( self.FButtonSCActionList );
  self.FButtonSCAction.Name := 'ClickShortcutAction';
  self.FButtonSCAction.OnExecute := self.ExecuteButtonShortcut;
  self.FButtonSCAction.ShortCut := TextToShortCut('CTRL+K');
  self.FButtonSCAction.Enabled := TRUE;
  self.FButtonSCAction.Visible := TRUE;
  self.FButtonSCAction.ActionList := self.FButtonSCActionList;
  self.Action := FButtonSCAction;

如果我使用此代码创建自定义控件,将其添加到工具栏,将其放置在新的 VCL Forms 应用程序中的窗体上,然后运行该应用程序,当我按下快捷键时什么也不会发生。如果我在没有此代码的情况下创建控件,请将其放置在窗体上并将 Actionlist 分配给窗体,然后将仅涉及创建操作并将其分配给组件的 Action 属性的代码行放入按钮的 onclick 事件处理程序中,然后它会正确响应快捷键。对于我的一生,我看不出有什么不同,但希望你们 Actions Delphi 专家可以...

此操作的目的是允许开发人员通过属性为对象检查器中的按钮分配自定义快捷方式。我想直接分配给“内置”操作,但无法找到如何访问其快捷方式属性。 (显然我可以通过其他 HotKey delphi 功能来做到这一点,如果有必要的话我也会这样做,但我也想了解操作,这似乎是一个很好的起点......)

最佳答案

您不需要在设计时创建 ActionList。在 Create 方法中使用以下代码:

  FButtonSCAction := TAction.Create(Self);
  FButtonSCAction.SetSubComponent(true);
  FButtonSCAction.OnExecute := ExecuteButtonShortcut;
  FButtonSCAction.ShortCut := TextToShortCut('CTRL+K');
  FButtonSCAction.Enabled := TRUE;
  FButtonSCAction.Visible := TRUE;
  Action := FButtonSCAction;
  if not (csDesigning in ComponentState) then
    begin
      FButtonSCActionList := TActionList.Create(aOwner);
      FButtonSCAction.ActionList := FButtonSCActionList;
    end;

在控件的运行时创建期间,您可能会遇到这样的情况:传递给控件的 aOwner 不是表单本身,而是另一个控件。在这种情况下,您必须调用从 aOwner 参数为您提供表单的函数,而不是使用 aOwner 创建操作列表。

function GetOwnerForm(Component: TComponent): TComponent;
begin
  Result := Component;
  while (Result <> nil) and (not (Result is TCustomForm)) do
    begin
      Result := Result.Owner;
    end;
end;

FButtonSCActionList := TActionList.Create(GetOwnerForm(aOwner));

关于delphi - 运行时分配的操作的快捷方式不会在自定义组件中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27053769/

相关文章:

delphi - 重载三个扩展记录的添加运算符

html - 创建具有两行表格的可重复 Angular 组件

facebook - 使用自定义开放图形对象将视频嵌入到时间轴上

qt - 如何在 Qt Creator 中将菜单点击与操作连接起来?

C# 在 X 秒后执行操作

delphi - Delphi中如何给变量赋值?

delphi - 如何计算文本文件中包含多个空格字符的所有单词

java - 为什么我的 JRadioButton 在这种情况下不起作用?

jsf - 根据 bool 值有条件地切换组件属性的值

德尔福2010 : How to save a whole record to a file?