Initializing Form Variables
The second way to initialize variables is to use an initialization event. Most Visual Basic programmers already know this technique because they’ve used the Form_Load event to initialize form properties and variables. You should also familiarize yourself with two other initialization events: Form_Activate and Form_Initialize.
When a form is loaded, the sequence of events is the following:
-
A form is a class, and all classes have an Initialize event. Form_Initialize is called (or fired, as control developers describe calling events) as soon as you touch any variable or property of a form. Use this event to ini-tialize variables private to the form. Normally, you should not touch any form or control properties here because doing so fires the next event.
-
Form_Load fires after Form_Initialize as the visual elements of the form are being created and default values are being assigned to properties. Normally, you should avoid doing anything that will draw something on the form because that causes an automatic firing of the next event. It might be tempting to call Show in Form_Load and then do further processing with the visible form, but you’re usually better off doing this in the next event.
-
Form_Activate fires after you have loaded and shown the form. It’s possible to load a form without showing it; in this case, Form_Activate isn’t fired until you call the Show method. Form_Activate is also called when you switch from one modeless form to another, or when you switch between MDI forms (but not when you return focus from
another application). If your application has modeless or MDI forms, don’t do anything in Form_Activate that you want to happen only once. Or use a static variable (such as fNotFirst) to protect against multiple initializations in Form_Activate.
The interactions between the three initialization events can be confusing. Sometimes trial and error is the only way to figure out the right initialization sequence for your application.