After you have added controls to a form and set their properties, the next step is to add code to the form that responds to control events and that manipulates the controls.
You use the code editor to write code that responds to control events. The code editor is described in Chapter 5, “Visual Basic Code Editor,” but you can open the code editor from the Windows Forms Designer.
An event handler is a code routine that catches an event raised by a control and takes some action. Almost all program action is started from an event handler. Even actions started automatically by a timer or when a form first appears begin when an event handler catches a timer’s events.
If you double-click a control on the Windows Forms Designer, Visual Studio creates an empty event handler to handle the control’s default event and it opens the event handler in the code editor. For example, the following code shows the event handler the IDE built for a Button control named Button1. The default event for a Button is Click, so this code is a Click event handler.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
Private Sub btnExit_Click() Handles btnExit.Click
End Sub
Another way to build an event handler and open the code editor is to select the control on the Windows Forms Designer. Then click the Events icon (the lightning bolt) near the top of the Properties window to make the window show a list of events for the control as shown in Figure 3-5. Double-click an event in the window to create an event handler for it and to open it in the code editor.
If you select more than one control in the Windows Forms Designer and then double-click an event, Visual Studio makes an event handler that catches the event for all of the selected controls. To create the following event handler, I selected three Buttons and double-clicked the Click event:
Private Sub Button2_Click(sender As Object, e As EventArgs) _
Handles Button3.Click, Button2.Click, Button1.Click
End Sub
Note that I added the line continuation in the first line of the preceding code so it would fit in the book. Visual Studio makes it all one long line.
The event handler’s name is Button2_Click instead of Button1_Click or some other name because Button2 was the “white box master” control for the selected controls. See the section “Selecting Controls” earlier in this chapter for more information about a selection’s “master” control.