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

时间:2015-04-19 08:51:31

标签: delphi custom-component

我创建了一个组件并为其添加了一个Tbutton。  现在我想为我的Component创建OnClick事件,当用户在运行时单击我的组件的Button时执行该事件 我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

@ 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;