• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 235
  • Last Modified:

Duplicating components runtime

Is there an easy way to duplicate any given component in your app at runtime?

One way is obviously to create a new one and set all the properties manually, but I'm looking for something more flexible.
0
Keijo
Asked:
Keijo
  • 2
1 Solution
 
TheNeilCommented:
What about using the Assign method?

The Neil =:)
0
 
alx512Commented:
Hi! This code work only for published properties.
Try it.

function CopyComponent(Component: TComponent; NewComponentName: String): TComponent;
var
  Stream: TMemoryStream;
  S: String;
begin
  Result := TComponentClass(Component.ClassType).Create(Component.Owner);
  S := Component.Name;
  Component.Name := NewComponentName;
  Stream := TMemoryStream.Create;
  try
    Stream.WriteComponent(Component);
    Component.Name := S;
    Stream.Seek(0, soFromBeginning);
    Stream.ReadComponent(Result);
  finally
    Stream.Free;
  end;
end;

procedure TForm1.CopyButtonClick(Sender: TObject);
var
  NumberEdit2: TNumberEdit;
begin
  NumberEdit2 := CopyComponent(NumberEdit1, 'NumberEdit2') as TNumberEdit;
  NumberEdit2.Top := NumberEdit2.Top + 50;
  InsertControl(NumberEdit2);
end;
0
 
alx512Commented:
Try TEdit or other standart VCL component
0
 
KeijoAuthor Commented:
Thanks, that works like charm! (had to make some adjustments and publish everything though)
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now