Form Control
We have studied the concept of event and controls in our earlier articles.
Let us elaborate on that in this article. We start with the elements of form
control.
Form Events
Visual Basic forms and controls can trigger dozens of events in your
applications. Forms, controls, and classes all have events. Let's look at some
of the events for forms, and examine how and when they occur.
To demonstrate form events, we create a new form and placed code like this in
the event procedure for each of the events:
Private Sub Form_Load()
Debug.Print "Load"
End Sub
For each event, the name of the event was sent to the debug window. Here was the
output:
Initialize
Load
Resize
Activate
Paint
' I closed the form here
QueryUnload
Unload
Terminate
There are other form events also, such as the click event, etc., but those
must be triggered by user actions or other code. These are the events that are
always triggered for forms and the generic order in which they occur. Let's take
a look at each.
- Initialize
This event occurs as the form is being loaded, but before the Load event. It
gives you the opportunity to initialize data that must be available when the
form is loading.
- Load
Load is the event most often used to initialize any dynamic components of
the form, such as private data, control arrays, or any other element of the
design that needs to be setup at run time rather than in design view.
- Resize
This event occurs whenever the window state (windowed, minimized, or
maximized) changes or whenever the form window is resized by the user. Here
is where you place code that is dependent on the form size or window state.
If, for example, you are building a text editor, you might resize a text box
to the internal size of the form in the Resize event.
- Activate
This event occurs whenever the form window gets the input focus. If you have
code that tracks the active form in the application, you might use this
event for that code.
- Paint
This is where VB actually draw the form on the screen. If you are drawing
directly on the form with graphics methods, that code might go in this
event.
- QueryUnload
This event is fired when the form is closed. You can use the event to
determine the way the form is being closed (through your own code, by the
user, or by Windows) and can also cancel the event and prevent the form from