Visual Basic Events
Programs need to do something in response to user actions and actions initiated by the operating system. Such actions, which are external to the program itself (although they may be triggered by the program) are called events. Traditional procedural programming languages create programs in which the execution path is almost entirely dictated by the program's code. A Windows application, however, is event-driven, in that the user can interact with different elements within the user interface, in any order they choose. The events do not occur in a pre-determined order, and the code that is executed will be the code that is associated with a specific event (referred to in Visual Basic as an event procedure), regardless of the order in which events occur. There are different types of events and different ways to trigger them. An event can be triggered in the following ways:
- User interaction - clicking a button, for example.
- Object event - a timer control can trigger a timer event.
- System event - the operating system can trigger events.
- Code - the program itself may cause an event to occur.
Events are most often triggered by some form of user interaction. Forms and their controls all have their own unique set of events that are specific to a particular type of object. A Button control, for example, has a number of events, including the Click event which is triggered when the user clicks on it, causing the code within the Click event to be executed. A Textbox control shares some events with the Button control (for example, the Click event) but has other events that the Button control does not, like the TextChanged event, which is triggered each time you enter or delete a character in a text box.
Sometimes objects trigger their own events. A common example is the Tick event of a Timer control (a control, incidentally, that is not visible to the user at run time). The Tick event will be triggered at a time interval specified (in milliseconds) in its Interval property. The operating system itself may initiate actions that trigger an event. For example, if a form is partially obscured by another application's window, and the application is closed by the user, Windows will redraw the area of the form that was previously hidden. This will require Visual Basic to invoke the form's Paint event.
An event may also be triggered by the program itself. Beware, however, of creating a recursive event. For example, the TextChanged event is triggered each time the text in a text box changes. If the event procedure defined for the event changes the text in the text box, it will trigger the event procedure . . . which causes the text in the text box to change . . . which triggers the event procedure . . . and so on, ad infinitum. Recursion can be a powerful programming technique for doing things like processing lists and queues, but in the example just described it simply causes an endless loop that will result in Windows returning a StackOverflow error.
To put some of these ideas into practice, start Visual Basic 2008 and create a new project called "Events", then follow the steps shown below.
- Right-click Form1.vb in the Solutions Explorer window, select Rename, and change the filename to EventsForm.vb.
- Change the form's Text property to read "Event Examples".
- Add a picture box to the form.
- Change the name of the picture box to picText.
- Double-click the picture box to access its event procedures.
The code window should look like the one illustrated below. Note the two drop-down lists at the top of the window. The first contains a list of all the objects of the current form (including the form itself), while the second contains all the events for the currently selected object. Because the currently selected object is the picTest picture box, its name appears at the currently selected object, while the second list displays the name of the default event for the currently selected object, which is Click.
The code window displays the empty Click event procedure for the picText object
The event declaration (the line that stats "Private Sub . . .") defines the structure of the event. It contains the name of the object, an underscore character (_), and the name of the event, followed by a set of parameters inside parentheses. Click on the drop-down list on the right to see the events that the picture box object supports, and select MouseDown from the list. You will see the code window change to look like the one illustrated below. You can see that the event declaration looks similar to the one defined for the Click event (scroll right using the scroll bar if you can't see all of the code).
An empty event procedure is created when you select an object's event
The MouseDown event of a form has two parameters:
- ByVal sender As Object - the text following ByVal is the name of the parameter, and the text following the word As indicates its data type. The sender parameter contains a reference to a generic object representing the control that triggered the event.
- ByVal e As System.Windows.Forms.MouseEventArgs - the e parameter contains a reference to an object of type System.Windows.Forms.MouseEventArgs, which has properties that relate to the MouseDown event.
Some of the more commonly used properties of the System.Windows.Forms.MouseEventArgs object are described in the table below.
|Properties of System.Windows.Forms.MouseEventArgs|
|Clicks||Returns the number of times the user clicked the mouse button.|
|Button||Returns the button that was clicked (left, middle, right).|
|Delta||Returns a positive or negative number indicating the number of|
clicks performed (forward or backward) with the mouse wheel.
|X||Returns the horizontal coordinate at which the pointer was|
located when the user clicked.
|Y||Returns the vertical coordinate at which the pointer was located|
when the user clicked.
|Location||Returns a Point object that contains the X and Y coordinates at|
which the pointer was located when the user clicked.
- Close the Events project down now and open the Image Viewer project.
- Add a label to the form by double-clicking the Label tool in the toolbox, and set its properties as shown below.
- Add a second label to the form and set its properties as shown below.
Your form should now look like the one shown below.
The form with its X: and Y: labels
- Double-click on the picture box to access its event procedures.
- Select MouseMove from the event list to create a new event procedure for the picture box (you can delete the Click event procedure that was created by default when you double-clicked the picture box).
- Enter the code below into the MouseMove event procedure.
lblX.Text = "X: " & e.X
lblY.Text = "Y: " & e.Y
Your code should now appear as shown below.
The empty MouseMove event procedure is created for you - just add the code to set each label's Text property
The code works by setting the Text property for each of the labels X: and Y: as the mouse moves around inside the picture box. For label X:, for example, the code will amend the Text property to read "X: n", where n is the current x-coordinate of the mouse pointer relative to the left-hand side of the picture box in pixels.
- Save the project, then run the program and move the mouse pointer around over the picture box. You will see the x and y coordinates change, and your form should look something like that illustrated below.
The x and y coordinates reflect the position of the mouse pointer
When you move the mouse pointer out of the picture box, the coordinates of the last point the mouse pointer was over are still displayed. In order to rectify this situation, we need to add some more code.
- Exit the Image Viewer application.
- In the form's code window, use the drop down arrows at the top of the window to select the picShowImage object, and then the MouseLeave event from the object's event list.
- Enter the code below into the MouseLeave event procedure.
lblX.Text = ""
lblY.Text = ""
- Run the program again, move the mouse pointer around inside the picture box, and then move the mouse out of the picture box. You will see that the labels disappear completely when the mouse pointer is not within the boundaries of the picture box.
Ideally, it would be nice if the coordinate labels were only visible when the mouse is over the picture box (as things stand, the X: and Y: labels are visible when the program first runs). You can initialise the values for these labels when the program runs as follows:
- Exit the Image Viewer application once more.
- In the form's code window, use the drop down arrows at the top of the window to select the ViewForm Events object (which is always at the top of the list), and then the Load event from the object's event list.
- Enter the code below into the Load event procedure.
lblX.Text = ""
lblY.Text = ""
- Run the program again. You should find that the X: and Y: labels are now only visible when the mouse pointer enters the picture box.