如何知道TButton单击是否执行了TAction?

问题描述

我在VCL应用程序中使用TAction和TButton。将“ TButtons操作”字段设置为现有操作可集中代码。

动作Execute方法如下:

void __fastcall MyFrame::MyActionExecute(TObject *Sender)
{
//Some action code
}

将MyAction分配给名为MyBtn的TButton并查看操作 ActionComponent

void __fastcall MyFrame::MyActionExecute(TObject *Sender)
{

  if(MyAction->ActionComponent == MyBtn)
  {
   //.. action code when the MyBtn was clicked..
  }
}

似乎工作良好。

但是,以编程方式调用MyAction的Execute方法 ,如下所示:

MyActionExcecute(NULL);

似乎没有将ActionComponent设置为NULL,而是“仍然”使用MyBtn作为ActionCompoent。因此,即使未单击按钮,上面的if语句的评估结果也为true。

问题是,处理按钮单击和手动调用动作执行方法的正确方法是什么?

我知道我可以检查Sender参数是否为NULL,如果是,我可以假定它不是按钮。

解决方法

仅当UI控件通过内部为自己创建的内部ActionComponent对象触发操作时,才设置操作的TBasicActionLink属性。链接的Execute()方法具有一个AComponent参数,控件将其Self / this指针传递给该参数,以在调用操作的{{ 1}}方法。

例如,这是VCL内部执行的操作:

ActionComponent
Execute()
procedure TControl.SetAction(Value: TBasicAction);
begin
  if Value = nil then
  begin
    ActionLink.Free;
    ActionLink := nil;
    ...
  end
  else
  begin
    ...
    if ActionLink = nil then
      ActionLink := GetActionLinkClass.Create(Self);
    ActionLink.Action := Value;
    ...
  end;
end;

因此,请勿直接调用您的procedure TControl.Click; begin { Call OnClick if assigned and not equal to associated action's OnExecute. If associated action's OnExecute assigned then call it,otherwise,call OnClick. } if Assigned(FOnClick) and (Action <> nil) and not DelegatesEqual(@FOnClick,@Action.OnExecute) then FOnClick(Self) else if not (csDesigning in ComponentState) and (ActionLink <> nil) then ActionLink.Execute(Self) // <-- HERE else if Assigned(FOnClick) then FOnClick(Self); end; 事件处理程序 。那根本不会更新动作。而是调用操作的Execute()方法。您只需要事先将操作的function TBasicActionLink.Execute(AComponent: TComponent): Boolean; begin FAction.ActionComponent := AComponent; // <-- HERE Result := FAction.Execute; end; 设置为NULL,例如:

OnExecute

documentation声明:

当用户单击客户端控件时,该客户端会在调用操作的ActionComponent方法之前设置MyAction->ActionComponent = NULL; MyAction->Execute(); 执行该操作后,该操作会将ActionComponent重置为nil(Delphi)或NULL(C ++)

但是,Execute不会自动重置,只有在UI控件下次决定自行执行该操作时才可以。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...