使用组件内部按钮的 Onclick 事件

Using Onclick event of button inside of component

我创建了一个组件并向其添加了一个 Tbutton。 现在我想为我的组件创建 OnClick 事件,当用户在 运行 时间点击我的组件的按钮时执行 我该怎么做?

@LU_RD的回答应该就是你要找的

我写了一个较小的示例,应该与您正在做的类似。

interface

TMyComponent = class(TCustomControl)
private
  embeddedButton: TButton;
  fOnButtonClick: TNotifyEvent;
  procedure EmbeddedButtonClick(Sender: TObject);
protected
  procedure DoEmbeddedButtonClick; virtual;
public
  constructor Create(AOwner: TComponent); override;
published
  property OnButtonClick: TNotifyEvent read fOnButtonClick write fOnButtonClick;
end;

implementation

// Attach embedded button event handler onto embedded button
constructor TMyComponent.Create(AOwner: TComponent);
begin
  // .. other code
  embeddedButton.OnClick := EmbeddedButtonClick;
  // .. more code
end;

// EmbeddedButtonClick fires internal overridable event handler;
procedure TMyComponent.EmbeddedButtonClick(Sender: TObject);
begin
  // If you want to preserve the Sender, extend this method
  // with a sender argument.
  DoEmbeddedButtonClick;
end;

procedure TMyComponent.DoEmbeddedButtonClick;
begin
  // Optionally if you need to do additional internal work
  // when the button is clicked, you can do it here.

  // Check if event handler has been assigned
  if Assigned(fOnButtonClick) then
  begin
    // Fire user-assigned event handler
    fOnButtonClick(Self);
  end;
end;