如何复制组件/控件?

时间:2012-02-27 16:47:44

标签: delphi delphi-7

  

可能重复:
  Duplicating components at Run-Time

我有一个TMyControlControl1),它有自己的属性/事件 如何创建具有完全相同属性/事件的重复实例Control2


更具体地说,我想用流媒体字段(以及一些事件)克隆现有的TADODataSet

object ADODataSet1: TADODataSet
  Connection = ADOConnection1
  CursorType = ctStatic
  AfterOpen = ADODataSet1AfterOpen
  CommandText = 'select top 10  * from Polls'
  Parameters = <>
  Left = 224
  Top = 40
  object ADODataSet1PollID: TGuidField
    FieldName = 'PollID'
    FixedChar = True
    Size = 38
  end
  object ADODataSet1Title: TWideStringField
    FieldName = 'Title'
    Size = 255
  end
  object ADODataSet1Description: TWideStringField
    FieldName = 'Description'
    Size = 4000
  end
  object ADODataSet1PollType: TIntegerField
    FieldName = 'PollType'
  end
end

由于您已关闭此问题,如果我提出新问题“如何使用持久字段复制TADODataSet,您是否会考虑重复?

2 个答案:

答案 0 :(得分:7)

以下代码可能会给出一些指示:

unit Unit130;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls;

type
  TForm130 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    edit2: TEdit;
  public
  end;

var
  Form130: TForm130;

implementation

{$R *.dfm}

procedure TForm130.Button1Click(Sender: TObject);
var
  component: TComponent;
  stream: TMemoryStream;
begin
  RegisterClass(TEdit);
  stream := TMemoryStream.Create;
  try
    stream.WriteComponent(edit1);
    stream.Position := 0;
    component := stream.ReadComponent(nil);
    edit2 := component as TEdit;

    { this is necessary to make the following InsertComponent work }
    edit2.Name := 'Edit2';
    InsertComponent(edit2);

    edit2.Parent := Self;
    edit2.Top := edit2.Top + 30;
  finally
    stream.Free;
  end;
end;

end.

答案 1 :(得分:4)

复制所有属性值。

没有默认机制。这是有原因的。您的请求的问题是您真的不希望所有设置都重复。例如:它是否应出现在同一位置且具有相同尺寸的同一父级?即使是,两者中哪一个应该在最顶端?