Creating a VCL Form Instance Using a Local Variable
Go Up to How To Build VCL Forms Applications
A safe way to create a unique instance of a modal VCL form is to use a local variable in an event handler as a reference to a new instance. If you use a local variable, it doesn't matter whether the form is auto-created or not. The code in the event handler makes no reference to the global form variable. Using RAD Studio, the following procedure creates a modal form instance dynamically. It (optionally) removes the second form's invocation at startup.
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 (optional).
- 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 > Other > Delphi Projects or C++Builder Projects and double-click the VCL Forms Application icon. The VCL Forms Designer displays Form1.
- Choose File > New > Other > Delphi Projects > Delphi Files or C++Builder Projects and double-click the Form icon. The VCL Forms Designer displays Form2.
To optionally 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.
- For Delphi, insert the cursor just above the event handler block and enter the following statement to define a local variable:
var FM: TForm2;
- For C++, enter the following variable declaration:
- Insert the cursor in the event handler block, and enter the following code:
FM := TForm2.Create(self); FM.ShowModal; FM.Free;
FM = new TForm2( this ); FM->ShowModal(); FM->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.
- With Form2 displayed, attempt to click on Form1 to activate it. Nothing happens.
- Click the X in the upper right corner of Form2. Form2 closes and Form1 becomes the active form.