Delphi RTTI 动态创建Form

无需引用单元,直接创建对应Form

  

procedure MyShowForm(FormName: string);
  var
    ctxRtti: TRttiContext;
    typeRtti: TRttiType;
    methRtti: TRttiMethod;
    LClass: TRttiInstanceType;
    aForm: TCustomForm;
  begin
    ctxRtti  := TRttiContext.Create;
    try
      for typeRtti in ctxRtti.GetTypes() do
      begin
        if SameText(typeRtti.Name, FormName) then
        begin
          LClass := typeRtti.AsInstance;
          aForm := LClass.MetaclassType.Create as TCustomForm;
          aForm.Create(Application);
          aForm.Show;
          aForm.BringToFront;
        end;
      end;
    finally
      ctxRtti.Free;
    end;
  end;

  MyShowForm('TForm2');


你可能感兴趣的:(delphi)