Delphi动态创建组件,并释放内存
开发所用delphi版本是xe2,效果图如下:
代码如下:
-----------------------------------------------------------------------------------------------------------------
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TForm1 = class(TForm) Panel1: TPanel; Button1: TButton; Edit1: TEdit; Memo1: TMemo; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } function getmaxval(myarray: array of Integer):Integer; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} var rec: Integer = 0; procedure TForm1.Button1Click(Sender: TObject); var i,j,m,n,p:Integer; edt: TEdit; arr: array of Integer; begin Inc(rec); //按钮点击次数 m := 0; n := 0; p := 0; Memo1.Clear; for i := 0 to Panel1.ControlCount - 1 do begin if Panel1.Controls[i] is TEdit then inc(m); //记录edit个数 end; SetLength(arr,m); Memo1.Lines.Add('创建组件前的记录:' + #13#10 + '--------------------------'); Memo1.Lines.Add('Edit组件个数:' + IntToStr(m) + #13#10 + '--------------------------'); for j := 0 to Panel1.ControlCount - 1 do begin if Panel1.Controls[j] is TEdit then begin if n <= m then begin arr[n] := TEdit(Panel1.Controls[j]).Top; Memo1.Lines.Add('Edit' + IntToStr(n + 1) + '的Top值:' + IntToStr(arr[n])); Inc(n); end else Break; end; end; p := getmaxval(arr); //记录panel里最下面的edit的top值 Memo1.Lines.Add('最大Top值:' + inttostr(p)); //动态创建Edit //TEdit.Create(),参数是一个AOwner: TComponent,只要是窗体上的组件都可以, //但必须要在创建后重新指明父组件的名称,否则没法显示 edt := TEdit.Create(Panel1); //指明了owner,可以不释放内存,窗口关闭时由父组件销毁 edt.Parent := Panel1; edt.Left := Edit1.Left; edt.Top := p + Edit1.Height + 3; edt.Width := Edit1.Width; edt.Height := Edit1.Height; edt.Text := 'Edit' + IntToStr(rec + 1); edt.Show; end; procedure TForm1.Button2Click(Sender: TObject); //释放内存,并初始化 var i,j,m:Integer; edts: array of TEdit; begin j := 0; //数组edts的键[key] SetLength(edts,rec + 1); //button1次数 + 原有的edit1 for i := 0 to Panel1.ControlCount - 1 do begin if Panel1.Controls[i] is TEdit then begin edts[j] := TEdit(Panel1.Controls[i]); Inc(j); end; end; for m := Length(edts) downto 1 do //edit1不释放,注意此处的downto,根据栈后进先出原则,否则会报错 begin try edts[m].Free; rec := 0; Memo1.Clear; except //ShowMessage('释放动态创建组件的内存失败!'); end; end; end; function TForm1.getmaxval(myarray: array of Integer):Integer; //遍历数组取得最大值 var i,max:Integer; begin max := myarray[0]; for i := 1 to Length(myarray) - 1 do begin if myarray[i] >= max then max := myarray[i]; end; Result := max; end; end.