Creating Forms Dynamically

From RAD Studio
Jump to: navigation, search

Go Up to Controlling When Forms Reside in Memory


You may not always want all your application's forms in memory at once. To reduce the amount of memory required at load time, you may want to create some forms only when you need to use them. For example, a dialog box needs to be in memory only during the time a user interacts with it.

To create a form at a different stage during execution using the IDE:

  1. Select the File > New > Form from the main menu to display the new form.
  2. Remove the form from the Auto-create forms list of the Project > Options > Forms page.This removes the form's invocation at startup. As an alternative, you can manually remove the following line from program's main entry point:
    Application.CreateForm(TResultsForm, ResultsForm);
    
    Application->CreateForm(__classid(TResultsForm), &ResultsForm);
    
  3. Invoke the form when desired by using the form's Show method, if the form is modeless, or ShowModal method, if the form is modal.

An event handler for the main form must create an instance of the result form and destroy it. One way to invoke the result form is to use the global variable as follows. Note that ResultsForm is a modal form so the handler uses the ShowModal method.

procedure TMainForm.Button1Click(Sender: TObject);
begin
  ResultsForm := TResultForm.Create(self);
  try
    ResultsForm.ShowModal;
  finally
    ResultsForm.Free;
  end;
end;
void __fastcall TMainMForm::FirstButtonClick(TObject *Sender)
{
    ResultsForm = new TResultsForm(this);
    ResultsForm->ShowModal();
    delete ResultsForm;
}

In the above example, note the use of try..finally. Putting in the line ResultsForm.Free; in the finally clause ensures that the memory for the form is freed even if the form raises an exception.

The event handler in the example deletes the form after it is closed, so the form would need to be recreated if you needed to use ResultsForm elsewhere in the application. If the form were displayed using Show you could not delete the form within the event handler because Show returns while the form is still open.

Note: If you create a form using its constructor, be sure to check that the form is not in the Auto-create forms list on the Project > Options > Forms page. Specifically, if you create the new form without deleting the form of the same name from the list, Delphi creates the form at startup and this event-handler creates a new instance of the form, overwriting the reference to the auto-created instance. The auto-created instance still exists, but the application can no longer access it. After the event-handler terminates, the global variable no longer points to a valid form. Any attempt to use the global variable will likely crash the application.

See Also