Create a Delphi Form From a String

Elevated view of programmers working on laptops

Maskot / Getty Images

There may be instances when you do not know the exact class type of a form object. You may only have the string variable carrying the name of the form's class, such as “TMyForm”.

Note that the Application.CreateForm() procedure expects a variable of type TFormClass for its first parameter. If you can provide a TFormClass type variable (from a string), you will be able to create a form from its name.

The FindClass() Delphi function locates a class type from a string. The search goes through all registered classes. To register a class, a procedure RegisterClass() can be issued. When the FindClass function returns a TPersistentClass value, cast it to TFormClass, and a new TForm object will be created.

Sample Exercise

  1. Create a new Delphi project and name the main form: MainForm (TMainForm).
  2. Add three new forms to the project, name them:
  3. FirstForm (TFirstForm)
  4. SecondForm (TSecondForm)
  5. ThirdForm (TThirdForm)
  6. Remove the three new forms from the "Auto-create Forms" list in the Project-Options dialog.
  7. Drop a ListBox on the MainForm and add three strings: 'TFirstForm', 'TSecondForm', and 'TThirdForm'. 
procedure TMainForm.FormCreate( Sender: TObject);
begin
RegisterClass(TFirstForm); RegisterClass(TSecondForm); RegisterClass(TThirdForm);
end
;

In the MainForm's OnCreate event register the classes:

procedure TMainForm.CreateFormButtonClick( Sender: TObject);
var
s : string;
begin
s := ListBox1.Items[ListBox1.ItemIndex]; CreateFormFromName(s);
end
;

Once the button is clicked, find the selected form's type name, and call a custom CreateFormFromName procedure:

procedure CreateFormFromName(
const FormName : string);
var
fc : TFormClass; f : TForm;
begin
fc := TFormClass(FindClass(FormName)); f := fc.Create(Application); f.Show;
end
; (* CreateFormFromName *)

If the first item is selected in the list box, the "s" variable will hold the "TFirstForm" string value. The CreateFormFromName will create an instance of the TFirstForm form.