> The term for this is "cloning" an object.
>
> There is no built in way of doing this in Delphi, and there are issues
> involved in any cloning operation; e.g. are you interested in a shallow
> clone (just the one object), or a deep clone (your one object, and all
> objects to which it refers)?
>
> Probably a google newsgroup search on Delphi+cloning+objects
> might give you
> a few ideas on how to progress...

If your object inherits from TComponent the following code will clone a
component. I have used it to clone TButtons and few other simple visual
components successfully.


unit Cloner;

interface

uses
  SysUtils, Classes, Controls;

function Replicate(C: TComponent): TComponent;

implementation

procedure CloneComponent(C1: TComponent; C2: TComponent);
//
// This procedure clones the properties of C1 and writes them to C2.
// C1 and C2 must be of the same type.  Use it for components that do
// not have an Assign method.
//
var
  theStream: TMemoryStream;
  tmpS:      string;
begin
  if C1.ClassType <> C2.ClassType then
    raise EComponentError.Create('Object types are incompatible');

  if C1 is TControl then
    TControl(C2).Parent := TWinControl(C1).Parent;

  theStream := TMemoryStream.Create; // Create the memory stream.

  with theStream do try
    tmpS    := C1.Name;
    C1.Name := EmptyStr;
    WriteComponent(C1);        // Write C1 properties to stream
    C1.Name := tmpS;
    Seek(0, soFromBeginning);  // Position to beginning of stream.
    ReadComponent(C2);         // read properties from stream into C2
  finally
    Free;                      // IAC, free stream.
  end;
end;

function Replicate(C: TComponent): TComponent;
//
// This function "replicates" component C and returns
// a new component whose type and properties match
// those of C.
//
begin
  Result := TComponentClass(C.ClassType).Create(C.Owner); // Create
component }
  CloneComponent(C, Result);                              // Clone it }
end;

end.

---------------------------------------------------------------------------
    New Zealand Delphi Users group - Delphi List - [EMAIL PROTECTED]
                  Website: http://www.delphi.org.nz
To UnSub, send email to: [EMAIL PROTECTED] 
with body of "unsubscribe delphi"
Web Archive at: http://www.mail-archive.com/delphi%40delphi.org.nz/

Reply via email to