Creating Controls at Runtime
In VCL, the rules for dynamically creating controls are more relaxed compared with uniGUI. For example, in uniGUI, forms and controls can not be created without an owner. In uniGUI, forms must be shown when they are created, while in VCL there is no such restriction.
Another important note here is regarding the lifetime management of dynamically created controls. When a control is created dynamically the correct practice is to let them be destroyed by their owners or parents. It is not recommended to destroy controls dynamically in code. Each control with an owner will be destroyed by its owner (or parent) when the owner itself is freed, so under normal conditions there is no need to write additional code to destroy dynamically created controls. The best practice is to allow user actions decide when a control must be freed. For instance, if you have a form which contains several dynamically created controls, these controls will be freed when the user closes the owner form.
Let's summarize some of the rules that must be followed when creating controls dynamically:
In the code below, a form is created dynamically. As you can see, the owner is the UniApplication object and the form is shown right after it is created.
procedure TMainForm.UniButton1Click(Sender: TObject);
begin
TUniForm1.Create(UniApplication).Show;
end;That syntax can be extended to modify form properties before showing it.
procedure TMainForm.UniBitBtn1Click(Sender: TObject);
begin
with TUniForm1.Create(UniApplication) do
begin
Color := clGray;
BorderStyle := bsNone;
ShowModal;
end;
end;In both examples, we don't keep an instance of the created form because in many cases it is unnecessary. A form should be considered as a standalone object which is used and discarded. Of course, you can keep a reference to a form instance, but you must be aware that uniGUI forms are dynamically destroyed when they are closed by the user, so that any variable holding the form's instance will be in an invalid state after the form is closed.
To create controls dynamically, we can use form's OnCreate or OnBeforeShow events. Actually, any other event can be used, but if you want to create many dynamic controls it is wise to do this before the form becomes visible.