同名派生的应用(转)

有时候,我们需要少量修改或增加已有控件的行为或属性,但又不想新写个控件注册到组件面板上或动态创建来用,可以通过同名控件派生来实现。

以下这个简单的例子,为 TPanel 增加了 OnPaint 事件:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;

type

  // 以相同类名派生一个子类
  TPanel = class(ExtCtrls.TPanel)
  private
    FOnPaint: TNotifyEvent;
  protected
    // 重载一个方法
    procedure Paint; override;
  public
    // 新定义一个事件
    property OnPaint: TNotifyEvent read FOnPaint write FOnPaint;
  end;

  TForm1 = class(TForm)
    pnl1: TPanel;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    procedure OnPnlPaint(Sender: TObject);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TPanel }

procedure TPanel.Paint;
begin
  inherited;
  if Assigned(FOnPaint) then
    FOnPaint(Self);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  // 新增加的事件只能在运行期动态关联
  pnl1.OnPaint := OnPnlPaint;
end;

procedure TForm1.OnPnlPaint(Sender: TObject);
begin
  // 这一句是可以执行到的
  pnl1.Canvas.TextOut(10, 10, 'Test');
end;

end.

按上面的方法,也可以这样。

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Buttons, StdCtrls;

type
  TSpeedButton = class(TButton)
  public
    constructor Create(Aowner: TComponent); override;
  end;


  TForm1 = class(TForm)
    SpeedButton1: TSpeedButton;
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TSpeedButton }

constructor TSpeedButton.Create(Aowner: TComponent);
begin
  inherited Create(AOwner);
  Caption := 'TSpeedButton to TButton';
end;

end.
原文地址:https://www.cnblogs.com/enli/p/1952579.html