如何动态copy一个控件。。。。。。999999999999999 lake_cx请进帮忙 ( 积分: 0 )

  • 主题发起人 主题发起人 wutaoqing
  • 开始时间 开始时间
W

wutaoqing

Unregistered / Unconfirmed
GUEST, unregistred user!
以下是您的代码:
function CreateComponentCopy(AComponent: TComponent): TComponent;
var
ms: TMemoryStream;
begin
Result := nil;
RegisterClass(TPersistentClass(AComponent.ClassType));
ms := TMemoryStream.Create;
try
ms.WriteComponent(AComponent);
ms.Position := 0;
Result := ms.ReadComponent(nil);
finally
ms.Free;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
with (CreateComponentCopy(MaskEdit1) as TWinControl) do
begin
Parent := Self;
Left := 10;
Top := 10;
end;
end;
问题:
我想在form1里面动态创建控件写代码,新创建的控件如何才可以放在form2上去呢??
也就是说,我想在form1上创建控件到form2里面去,该怎么办??
 
lake_cx:
copy了你刚才给的代码,但是出现了一个错误,当程序运行到
Result := ms.ReadComponent(Result);这里时>>
提示错误:"A component namede Edit1 already exists"
 
function CreateComponentCopy(AComponent, Owner: TComponent): TComponent;
var
OldName: string;
ms: TMemoryStream;
begin
Result := nil;
RegisterClass(TPersistentClass(AComponent.ClassType));
OldName := AComponent.Name;
AComponent.Name := '';
ms := TMemoryStream.Create;
try
ms.WriteComponent(AComponent);
ms.Position := 0;
Result := TComponentClass(AComponent.ClassType).Create(Owner);
Result := ms.ReadComponent(Result);
Result.Name := '';
finally
AComponent.Name := OldName;
ms.Free;
end;
end;

然后
AWinControl := CreateComponentCopy(MaskEdit1, Form2) as TWinControl;
AWinControl.Parent := Form2;
 
接受答案了.
 
后退
顶部