When you add a new form to a Delphi project, a form and its associated unit is included in the application.
In all Delphi versions up until Delphi 2007 any newly added form will be placed in the "Auto-create forms" list of the "Project - Options - Forms" dialog. This results in the auto creation of the form when the applications starts.
If you do not manually remove forms from the "Auto-create forms" list to the "Available forms" list, Delphi will create all the forms listed - even the ones that you want to be displayed modally and the ones that you will maybe use, or use just a few times during the lifecycle of the application.
If all the forms are created at program's startup, program will use "too" much memory - memory that it is not needed (at "this" time) for the program to run. One might call this a memoy leak!
Note: any newly added form to Delphi 2007 (and above) will be placed in the "Available forms" list.
What is "var Form1 : TForm1;"?
By design, the source code skeleton for an empty form will look like:unit Unit1;If this form is in the "AutoAuto-create forms" list, the program's source code will include a line like:
interface
uses
Windows, Messages, SysUtils, Variants, Classes,
Graphics, Controls, Forms, Dialogs;
type
TForm1 = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
end;
//WHAT IS THIS FOR?!
var
Form1: TForm1;
implementation
{$R *.dfm}
end.
Application.CreateForm(TForm1, Form1) ;CreateForm creates a new form of the type specified by the first parameter: FormClass, and assigns it to the variable given by the second parameter: Reference. The owner of the new form is the Application object.
In the above case a new form named "Form1" will be created by the application.
Since the variable "Form1" is declared automatically in the interface section of the Form1's unit - it is global to that unit - meaning that it can be read and written to from any unit using this unit.
The project's source code unit uses all the units in the project - thus "Form1" is not "undeclared identifier" there.
Do I need the Form1 global variable?
Yes and no. If you remove the form from the "Auto-create forms" list - remove the "Form1" variable also.For those forms that will be displayed modally - thus created on the fly at run time, this is not needed. What's more you should remove the Form1 variable declaration to prevent from the accidental usage.
Of course, the question is how would you dynamically create a form in Delphi?
When the form is created automatically, because you actually need it to be created - then obviously you will leave this global form variable declaration. When you need to access Form2 from Form1 you will use the "Form2" global variable.
Note: never leave the default "FormX" name!
Delphi tips navigator:
» Impementing UnQuickSort in Delphi - How to Use the TListSortCompare function
« How Much Memory Is Your Delphi Program Occupying?

