1. Computing & Technology

Discuss in my forum

How to Clone a Delphi Form

By , About.com Guide

Creating Delphi objects (forms, components, etc) dynamically, at run-time, is a "standard" coding technique for Delphi developers. Almost every Form that you want to show modally will be created dynamically, displayed to the user and freed from the memory.

Besides instantiating Delphi Forms dynamically, you can decide to create a *clone* of an existing form - by using the TMemoryStream class.

Note: when you create a new clone from an existing form, the clone's OnCreate will not execute.

Here's how:

 procedure FormClone(form : TForm) ;
 var
    ms : TMemoryStream;
    clone : TForm;
 begin
    ms := TMemoryStream.Create;
    try
      ms.WriteComponent(form) ;
      ms.Position := 0;
      clone := TFormClass(form.ClassType).CreateNew(Application) ;
      ms.ReadComponent(clone) ;
 
      clone.Left := form.Left + 10;
      clone.Top := form.Top + 10;
      clone.Show;
    finally
      ms.Free;
    end;
 end;
 

//Usage procedure TForm1.Button1Click(Sender: TObject) ; begin    FormClone(Form1) ; end;

Delphi tips navigator:
» How to Remove the "Today" Mark from the TDateTimePicker
« How to Change the Colors of the TProgressBar

©2012 About.com. All rights reserved.

A part of The New York Times Company.