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.
KeijoAsked:
Who is Participating?
 
alx512Connect With a Mentor Commented:
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
 
TheNeilCommented:
What about using the Assign method?

The Neil =:)
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.