Article number: KB000028
Related blocks:
Application form development means that the forms are populated with components, then component properties and events are configured. A large number of components added in form design mode, make the form loading more time-consuming and use more memory. If some of the components are not displayed on the form all the time, but are shown conditionally, they can be created dynamically at the runtime instead of being added to the form. The code should have declared a variable with the corresponding type:
Class TESTForm: Form
btnRun: Button;
t: Timer;
//...
To create a component, the user needs to initialize an instance of the corresponding class using the New keyword and assign value to the declared variable. If a visual component is created (a component inherited from IControl interface), the user needs to use the Parent property to indicate the parent component in the area of which the created component is drawn. If the form itself is the parent component, the user can indicate the reserved Self ID as the value of the Parent property. Indicating parent component enables the user to remove created components correctly after the form finishes working:
//...
btnRun := New Button.Create;
btnRun.Parent := Self;
//...
It is not necessary to indicate parent component for non-visual components (inherited form the IComponent interface). Non-visual components can be used right after initializing the variable of the respective class.
//...
t := New Timer.Create;
t.Enabled := False;
//...
Procedures with corresponding signature should be created to handle components' events. To subscribe a component to an event, indicate procedure name as the value of the corresponding event:
//...
//Event handler for OnClick
Sub btnOnClick(Sender: Object; Args: IMouseEventArgs);
Begin
t.Enabled := True;
End Sub btnOnClick;
//Timer event handler
Sub OnTimer(Sender: Object; Args: IEventArgs);
Begin
End Sub OnTimer;
//...
//...
//Components subscription for events
btnRun.OnClick := btnOnClick;
t.OnTimer := OnTimer;
//...
When a component gets subscribed to an event, additional references to this event are created. If the component is a non-visual one, or the parent component is undefined, these references do not let the garbage collector clean the memory allocated to the component after the form runtime is completed. This results in keeping the object in memory. To avoid memory leakage, use the Dispose operator to delete components in such cases:
Sub TESTFormOnClose(Sender: Object; Args: IEventArgs);
Begin
Dispose t;
End Sub TESTFormOnClose;
If the user needs to delete a visual component at the form runtime, he should use the FreeComponent method together with the operator Dispose. FreeComponent removes visual part of the component, while Dispose deletes the component instance and frees the memory:
//...
FreeComponent(btnRun);
Dispose btnRun;
//...
See also: