Mega Code Archive

 
Categories / Delphi / OOP
 

Clone a Control with all its Childcontrols

Title: Clone a Control with all its Childcontrols Question: How can I Clone a Control-Component with all of its Childcontrols Answer: unit Unit1; //Clone a Control with all its Childcontrols interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, ComCtrls; type TForm1 = class(TForm) Panel1: TPanel; ComboBox1: TComboBox; Edit1: TEdit; BitBtn_CloneComtrolWithItsChildcontrols: TBitBtn; StatusBar1: TStatusBar; procedure BitBtn_CloneComtrolWithItsChildcontrolsClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.BitBtn_CloneComtrolWithItsChildcontrolsClick(Sender: TObject); function CloneComponent(AAncestor: TComponent): TComponent; var XMemoryStream: TMemoryStream; XTempName: string; begin Result:=nil; if not Assigned(AAncestor) then exit; XMemoryStream:=TMemoryStream.Create; try XTempName:=AAncestor.Name; AAncestor.Name:='clone_' + XTempName; XMemoryStream.WriteComponent(AAncestor); AAncestor.Name:=XTempName; XMemoryStream.Position:=0; Result:=TComponentClass(AAncestor.ClassType).Create(AAncestor.Owner); if AAncestor is TControl then TControl(Result).Parent:=TControl(AAncestor).Parent; XMemoryStream.ReadComponent(Result); finally XMemoryStream.Free; end; end; var aPanel: TPanel; Ctrl, Ctrl_: TComponent; i: integer; begin //handle the Control (here Panel1) itself first TComponent(aPanel) := CloneComponent(Panel1); with aPanel do begin Left := 5; Top := 8; end; //now handle the childcontrols for i:= 0 to Panel1.ControlCount-1 do begin Ctrl := TComponent(Panel1.Controls[i]); Ctrl_ := CloneComponent(Ctrl); TControl(Ctrl_).Parent := aPanel; TControl(Ctrl_).Left := TControl(Ctrl).Left; TControl(Ctrl_).top := TControl(Ctrl).top; end; end; procedure TForm1.FormCreate(Sender: TObject); begin //make StatusBar1, BitBtn its parentcontrol BitBtn_CloneComtrolWithItsChildcontrols.Parent := StatusBar1; BitBtn_CloneComtrolWithItsChildcontrols.Left := 2; BitBtn_CloneComtrolWithItsChildcontrols.Top := 2; end; end.