如何动态创建新的形式并从Delphi中的现有形式继承表单



在Delphi中有任何方法可以在动态创建一个之前从现有形式继承?我知道如何使用tobjects.create()动态创建新的形式,但是我需要创建一个与已经创建的表单完全相似的形式,通过在创建新表单上继承该表单。

   var
       Form2: TForm1;
    begin
       Form2 := TForm1.create(nil);
       try
          // now form2 is exactly "like" form1 when it was created 
          Form2.Top := Form1.Top;
          Form2.Left := Form1.Left;
          // now some of Form2's properties are like Form1's are now                                              
          Form2.ShowModal;
       finally
          Form2.Free;
       end;

所以问题是,"喜欢"是什么意思?如果自创建以来的运行时更改了Form1,则需要在创建form2之后将相同的运行时更改应用于形式。继承不能为您做到这一点。继承是"容器",而不是数据。要复制表单的"数据",您需要编写一个过程,该过程需要将Form2的所有属性值设置为Form1的属性值。也许,只需复制您关心的属性即可。

尝试此

interface
uses Forms, SysUtils, Classes, Controls;
type
    TCommonFormClass = class of TCommonForm;
    TCommonForm = class(TForm)
    private
      // Private declaration
    public
      // Public declaration
      constructor Create(Sender: TComponent); virtual;
    end;
implementation 
constructor TCommonForm.Create(Sender: TComponent);
begin
  inherited Create(Sender);
  // do other
end;

和您的孩子形式将像这样

type
    TMyForm = class(TCommonForm)
    private
        // Private declaration
    public
        // Public declaration
    end;
implementation
{$R *.dfm}
end.

创建孩子使用:

procedure CallChild;
var MyForm: TMyForm;
begin
  MyForm:= TMyForm.Create(nil);
  try    
    MyForm.ShowModal;
  finally
    MyForm.Free;
  end;
end;

最新更新