Search code examples
delphidelphi-xe3firemonkey-fm2

Dynamically create form by name?


Is there a way to create forms dynamically by only their names; The concept goes like this. I have a main form, and by some user selection, a number of predefined forms must be created and docked on tabitems on a pagecontols on the main form. I do know the names of the forms and i do know when to create each one of those, but i would like to know if a better way of creating these forms by a single procedure call, and not having all of these information in my code.

Its Delphi XE3 firemonkey, on win 7.

Thanks in advance for any help


Solution

  • Apparently on Firemonkey Delphi doesn't automatically register form classes to be available by name, so you'll first need to add something like this to the end of the unit that holds your form class:

    unit Form10;
    [ ... ]
    // Right before the final "end."
    initialization
      RegisterFmxClasses([TForm10]);
    end.
    

    This will automatically register TForm10 so it'll be available by name. Next you can use this kind of code to create a form at Runtime by it's class name:

    procedure TForm10.Button1Click(Sender: TObject);
    var ObjClass: TFmxObjectClass;
        NewForm: TCustomForm;
    begin
      ObjClass := TFmxObjectClass(GetClass(ClassName));
      if ObjClass <> nil then
      begin
        NewForm := ObjClass.Create(Self) as TCustomForm;
        if Assigned(NewForm) then
          NewForm.Show;
      end
    end;