Create an exact copy of TPanel on Delphi5

I have a pnlMain TPanel where several dynamic TPanels (and pnlMain are their Parents) are created in accordance with user actions, data verification, etc. Each panel contains one color grid full of lines. Besides panels, there are some open source arrow components and an image. The whole bunch of things.

Now I want the user to be able to print this panel (I asked how to do this on this issue ), but before printing, the user needs to provide a new form containing a copy of pnlMain. In this form, the user needs to make some changes, add several components, and then print his customized copy of pnlMain. After printing, the user will close this form and return to the original form with the original pnlMain. And, as you can guess, the original pnlMain should remain intact.

So, is there any smart way to copy the entire TPanel and its contents? I know I can do it manually, iterating through the pnlMain.Controls list.

+4
source share
3 answers

Code based as iteration on child controls, but not bad anyway; -)

procedure TForm1.btn1Click(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(pnl1); with aPanel do begin Left := 400; Top := 80; end; //now handle the childcontrols for i:= 0 to pnl1.ControlCount-1 do begin Ctrl := TComponent(pnl1.Controls[i]); Ctrl_ := CloneComponent(Ctrl); TControl(Ctrl_).Parent := aPanel; TControl(Ctrl_).Left := TControl(Ctrl).Left; TControl(Ctrl_).top := TControl(Ctrl).top; end; end; 

Delphi3000 code article

+3
source

Too much code ... ObjectBinaryToText and ObjectTextToBinary do a great job of streaming. There is a code example in Delphi 7, I don’t know, 2009 (or 2006, never bothered to look) is still there. See the D5 help file for these functions (there is no d5 here).

+2
source

I would do this using RTTI to copy all the properties. You still have to go through all the controls, but when you need to set property values, RTTI can help automate the process. You can give an example at the bottom of this article , where you will find a link to some helper code, including the CopyObject procedure.

+1
source

All Articles