Dynamically Creating a VCL Modal Form
Go Up to How To Build Windows VCL Applications
You may not want all your VCL application's forms in memory at once. To reduce the amount of memory required at load time, your application can create forms only when it needs to make them available for use. A dialog box, for example, needs to be in memory only during the time the user interacts with it. Using RAD Studio, the following procedure creates a modal form dynamically. The main difference between dynamically creating a form and displaying an auto-created VCL form is that you remove the second form's invocation at startup and write code to dynamically create the form.
Building this VCL application consists of the following steps:
- Create the project directory.
- Create two forms for the project.
- Remove the second form's invocation at startup.
- Link the forms.
- Create a control on the main form to create and display the modal form; then write the event handler.
- Build and run the application.
To create the two forms
- Choose File > New > Windows VCL Application - Delphi or File > New > Windows VCL Application - C++Builder.
- Choose File > New > VCL Form - Delphi or File > New > VCL Form - C++Builder accordingly.
To remove Form2's invocation at startup
- Choose Project > Options > Forms. The Project Options dialog displays.
- Select Form2 in the Auto-create forms list and click [>]. Form2 is moved to the Available forms list.
- Click OK to close the dialog.
To link Form1 to Form2
- Select Form1 and choose File > Use Unit . The Uses Unit dialog displays.
- Select Form2 (the form that Form1 needs to reference) in the dialog.
- Click OK. For Delphi, a uses clause containing the unit name Unit2 is placed in the implementation section of Unit1. For C++, the #include "Unit2.h" directive is added to Unit1.h.
To display Form2 from Form1
- Select Form1, if necessary; then, from the Standard page of the Tool Palette, place a TButton on the form.
- In the Object Inspector with Button1 selected, double-click the OnClick event on the Events tab. The Code Editor displays with the cursor in the TForm1.Button1Click (Delphi) or TForm1::Button1Click (C++) event handler block.
- Enter the following event handling code:
Form2 := TForm2.Create(self); try Form2.ShowModal; finally Form2.Free; end;
Form2 = new TForm2( this ); try { Form2->ShowModal(); } __finally { Form2->Free(); }
To build and run the application
- Save all files in the project; then choose Run > Run. The application executes, displaying Form1.
- Click the button. Form2 displays.
- Click the X in the upper right corner of the form. Form2 closes and Form1 becomes the active form.