To sonie:
constructor Form1.Create(AOwner:tComponent);override;
begin
inherited Create;
btn:=TButton.Create(this);//self
end;
btn由Form1释放,刚才我已经测试过了。哈哈
测试控件
unit TestButton;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TTestButton = class(TButton)
private
{ Private declarations }
s:TstringList;
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner:TComponent);override;
Destructor Destroy;override;
published
{ Published declarations }
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TTestButton]);
end;
{ TTestButton }
constructor TTestButton.Create(AOwner: TComponent);
begin
inherited;
s:=TStringList.Create;
end;
destructor TTestButton.Destroy;
begin
s.free;
inherited;
end;
end.
主窗体
unit Main;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, Menus;
type
TMainForm = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
end;
var
MainForm: TMainForm;
implementation
uses Unit1;
{$R *.DFM}
procedure TMainForm.Button1Click(Sender: TObject);
begin
form1:=TForm1.create(self);
end;
procedure TMainForm.Button2Click(Sender: TObject);
var
i:integer;
begin
i:=integer(form1);
TForm(i).free;
end;
end.
{dfm}
object MainForm: TMainForm
Left = 214
Top = 112
Width = 409
Height = 249
Caption = 'MainForm'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = True
PixelsPerInch = 96
TextHeight = 13
object Button1: TButton
Left = 72
Top = 40
Width = 75
Height = 25
Caption = 'Button1'
TabOrder = 0
OnClick = Button1Click
end
object Button2: TButton
Left = 200
Top = 40
Width = 75
Height = 25
Caption = 'Button2'
TabOrder = 1
OnClick = Button2Click
end
end
测试窗体
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, TestButton;
type
TForm1 = class(TForm)
TestButton1: TTestButton;
private
{ Private declarations }
//s:TStringList;
public
{ Public declarations }
//constructor Create(AOwner:TComponent);override;
//destructor Destroy;override;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
{ TForm1 }
{constructor TForm1.Create(AOwner: TComponent);
begin
inherited;
s:=TStringList.create;
end;
destructor TForm1.Destroy;
begin
s.Free;
inherited;
end;}
end.
{dfm}
object Form1: TForm1
Left = 226
Top = 227
Width = 544
Height = 375
Caption = 'Form1'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object TestButton1: TTestButton
Left = 160
Top = 40
Width = 75
Height = 25
Caption = 'TestButton1'
TabOrder = 0
end
end
你可以将测试PAS中的注释部分打开来测试,你会看到是怎样释放对象的。