Mega Code Archive

 
Categories / Delphi / Forms
 

Show a form by its form class name

Title: Show a form by its form class name Question: How can I create and show a form using the form class name without referencing the form unit. Answer: The method introduced is quite useful when you want to modularize your project by removing dependencies between modules. To achieve the task, you need to 1. Add this line to end of the form unit (eg. Form1.pas) as follows: Initialization RegisterClass(TForm1); This will ensure the form class can be retrieved by its name across the project, even before Form1 is created. 2. Use the following procedure to show the form procedure ShowForm( FormClassName:string); var aFormClass : TFormClass; aForm: TForm; begin AFormClass := TFormClass(FindClass(FormClassName)); AForm := AFormClass.Create(Application.MainForm); AForm.ShowModal; AForm.Free; end; This procedure can reside in a common unit. 3. Use the ShowForm procedure as follows: procedure TMainForm.btnShowFormClick(Sender: TObject); begin ShowForm('TForm1'); end;