VB6 forms have a well-defined life cycle, which is important for programmers to understand. The first stage in this cycle is when the form is created but is not yet loaded. This stage begins when you call the form's Show method, or at the start of program execution if the form is the startup form. During this state, the Form_Initialize event fires and code in the event procedure (if there is any) executes. Normally when the Form_Initialize event procedure has completed the form is loaded; however, code like this can cause a form to be created and the Form_Initialize event to fire, without the form being loaded:
Dim f As Form2
Set f = New Form2
A form can remain in the created but not loaded state even if you call a user-written form procedure. If you set a form property, or call a built-in method such as Move, or set a property of a control on the form, it will be loaded.
The second stage is when the form is loaded. At this point, the form's controls are created and loaded, and the form has a window complete with a window handle (hWnd) and a device context (hDC). The Form_Load event fires at this time, but the form is not necessarily shown; it is in the loaded but not shown state.
While most forms move directly from this state to being shown, some programming techniques leave a form in the loaded but not shown state in order to use the functionality of controls on the form without displaying them (e.g., to use a Timer control to time events, or to utilize DDE events). Most forms progress to being loaded and shown, most often by a call to the form's Show method. In this state, the user can interact with the form and its controls.
Calling a form's Hide method moves it from the loaded and shown state to the loaded but not shown state. The form remains in memory and its properties (and its control properties) remain intact. The form can be shown again, but it's important to know that showing the form again does not trigger the Load event. This event procedure is executed only once in a form's life cycle.
A form is finally unloaded when the Unload statement is called on it or when the program terminates. If the form has been loaded, then calling Unload fires its QueryUnload and Unload events in that order. If the form has been created but not loaded, you can call Unload on it but the QueryUnload and Unload events will not fire.
When unloaded, a form is removed from the Forms collection. It is not actually destroyed, however, until all references to it are set to Nothing. Before this is done, it remains in the created but not loaded state. Once all references are set to Nothing, then the form is destroyed, the Terminate event fires, and the memory and resources the form used are released.
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!