自定义组件如何处理其子项的事件?

时间:2013-04-06 08:07:08

标签: delphi events custom-controls

我正在设计一个面板后代组件,上面有一个按钮控件:

THidePanel = class(TPanel)
private
  TActivateButton: TButton;
public
  constructor Create(aOwner: TComponent); override;
  procedure WMSize(var Msg: TWMSize); message WM_SIZE;
  procedure HideComponents;
end;

该组件如何处理其TActivateButton控件的OnClick事件?

1 个答案:

答案 0 :(得分:8)

由于按钮是组件专用的,您只需将事件处理程序附加到它,即

THidePanel = class(TPanel)
  ...
  private
    procedure H_ActivateButtonClick(Sender: TObject);
  ...
end;

constructor THidePanel.Create(aOwner: TComponent);
begin
  inherited;
  ...
  FActivateButton := TButton.Create(Self);
  FActivateButton.Parent := Self;
  FActivateButton.OnClick:= H_ActivateButtonClick;
end

procedure THidePanel.H_ActivateButtonClick(Sender: TObject)
begin
  // button is clicked!
end

如果您还需要向组件的最终用户提供事件,则需要添加TNotifyEvent属性并从内部处理程序调用它,即

THidePanel = class(TPanel)
  private
    FOnActivateBtnClick: TNotifyEvent;
  ...
  published
    property OnActivateButtonClick: TNotifyEvent read FOnActivateBtnClick write FOnActivateBtnClick;
end;

procedure THidePanel.H_ActivateButtonClick(Sender: TObject)
begin
  // button is clicked!
  ...
  // fire the end user event
  if(Assigned(FOnActivateBtnClick))then FOnActivateBtnClick(Self);
end