Tuesday, November 5, 2019

How to Create a Delphi Form from a String

How to Create a Delphi Form from a String 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 forms 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 Create a new Delphi project and name the main form: MainForm (TMainForm).Add three new forms to the project, name them:FirstForm (TFirstForm)SecondForm (TSecondForm)ThirdForm (TThirdForm)Remove the three new forms from the Auto-create Forms list in the Project-Options dialog.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 MainForms 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 forms 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.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.