Question

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

Was it helpful?

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;

OTHER TIPS

You can only create objects when you have a class reference for it. To get a class reference for something given its string name, call FindClass. Call the constructor on the result. You may have to type-cast the result to a different metaclass before the compiler will allow you to access the constructor you want. In the VCL, you might use TFormClass, but plain old TComponentClass will work, too, since all FireMonkey objects are descendants of TComponent; the important part is that you have access to the right constructor, and that's where the one you need is introduced.

It only works for classes that have been registered. Your form classes should be registered by Delphi automatically, but if they're not, you can call RegisterClasses manually, or RegisterFmxClasses if you need to put your classes in groups.

Delphi.About.com has a VCL demonstration.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top