| Creating a Delphi Form from a String | ||||||||||||||||||||||
| Here's how to create an instance of a Delphi form, from its name. Example: if a string 'TMyForm' is provided, a new form of type TMyForm should be created ... | ||||||||||||||||||||||
Suppose you have a bunch of forms in your application (like you probably do). Of course, much of those forms get created dynamically at run time (and are removed from the "Auto-Create Forms" list in the Project properties window).
Let's say you have a form named "MyForm" where the class name is "TMyForm" you want to create. To create an instance of the "MyForm" form, at run-time, you could use the next code (to have it displayed modally, and freed as soon as it gets closed):
Or, you could set the "Application" to be the owner of the MyForm form, and issue a command like (to have it created and freed at a later time):
Now, what if you *do not* know the exact class type of a form object. What if you only have the string variable carrying the name of the form's class, as 'TMyForm'? You cannot use any of the code samples provided above. Application.CreateForm expects a variable of a TFormClass type NOT a string. You most certainly cannot use 'TmyForm'.Create(...)!
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, we cast it to TFormClass, and a new TForm object can be created!
An example ![]() In the MainForm's OnCreate event register the classes:
Once the button is clicked, we find the selected form's type name, and call a custom CreateFormFromName procedure:
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:
That's it! ![]() If you need any help with the code, be sure to post your questions on the Delphi Programming Forum.
|
||||||||||||||||||||||



