VB .NET Chapter 11 Events in VB .NET

The Click Event

What is an Event?

An event is something that happens. Your birthday is an event. So is Christmas. An event in programming terminology is when something special happens. These events are so special that they are built in to the programming language. VB.NET has numerous Events that you can write code for. And we're going to explore some of them in this section.
We'll start with all that mysterious code for the Button's Click Event.


Exploring the The Click Event

Buttons have the ability to be clicked on. When you click a button, the event that is fired is the Click Event. If you were to add a new button to a form, and then double clicked it, you would see the following code stub:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub
This is a Private Subroutine. The name of the Sub is Button1_Click. The Event itself is at the end: Button1.Click. The Handles word means that this Subroutine can Handle the Click Event of Button1. Without the arguments in the round brackets, the code is this:
Private Sub Button1_Click( ) Handles Button1.Click
You can have this Button1_Click Sub Handle other things, too. It can Handle the Click Event of other Buttons, for example. Try this.
  • Start a New project
  • Give it the name it Events
  • When you new Form appears, add two Buttons to it
  • Double click Button1 to bring up the code
  • At the end of the first line for the Button, add this:
Handles Button1.Click, Button2.Click
Add a message box as the code for the Button. Your code window might then look like this (we've used underscores to spread the code out over three lines) :
The code window
Run your programme, and then click both of the buttons in turn. The same message box appears, regardless of which one you clicked.
The reason it did so was because the Events that the Button1.Click Subroutine can Handle are at the end: the Events for Button1.Click AND Button2.Click.
You can add as many Events as you want on the End. As long as the Subroutine can Handle them, the Event will happen. For example, you could create two more buttons, and then add the Click Event on the end of the first button:
Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click
When you click any of the four button, the code inside of the Button1_Click Subroutine will fire.
However, if you double clicked button2 to try to bring up its coding window, you'd find that the cursor is flashing inside of the code for Button1_Click. Because you've attached the Click Event of button2 to the Button1 Subroutine, you can't have a separate Click Event just for Button2. This Click Event is Handled By the Subroutine called Button1_Click.

 

Event Arguments

The arguments for a Button's click event, the ones from the round brackets, are these two (2012 users won't see the ByVal keyword):
ByVal sender As System.Object, ByVal e As System.EventArgs
This sets up two variable: one called sender and one called e. Instead of sender being an integer or string variable, the type of variable set up for sender is System.Object. This stores a reference to a control (which button was clicked, for example).
For the e variable, this is holding an object, too - information about the event. For a button, this information might be which Mouse Button was clicked or where the mouse pointer was on the screen.
But because this is the Click Event, there's not much more information available: either the button was clicked or it wasn't.
But you can use other Events available to the button. One of these is the MouseDown Event. The information for the event would be which button was clicked, where the mouse pointer was when the mouse button was held down, and something called Delta (a count of how many notches have been rotated on a mouse wheel).
Let's explore the MouseDown Event.

The MouseDown Event in VB .NET

The MouseDown event is available to many controls on the form. A Form can detect when the mouse was held down on it; a textbox can detect when the mouse was held down inside of it; and a Button can detect which mouse button was held down to do the clicking.
We'll see how it all works right now.

First, delete the all but one of the buttons on your form. (You can right click on a control to delete it. If you haven't been following along from the previous lesson, then just create a new project. Add a Button to your form, and leave iton the default name of Button1.)
Go back to your coding window, and delete any code for the button on your form. Delete any Handles code except for Handles Button1.Click. Your coding window should look something like this one (we've used underscores to spread the code out over three lines):
The coding window, with the Event at the top
Right at the top of the code window, it says Button1 and Click. The lightning bolt next to Click signifies that it is an Event. If you click the drop down box, you'll see a list of other available events:
Select the MouseDown event from the list
Scroll down and find the MouseDown event, as in the image above. When you click on it, a new code stub appears, this one (ours looks a bit messy):
Private Sub Button1_MouseDown(ByValsender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseDown
End Sub
This is a Private Subroutine called Button1_MouseDown. Notice that it Handles the Button1MouseDown event, and not Button1.Click.

 

Exploring the Event Arguments

In between the round brackets of the Subroutine, we still have ByVal sender As Object. But we have a new argument now (2012 users will just see e As MouseEventArgs):
ByVal e As System.Windows.Forms.MouseEventArgs
The name of the variable is still e. But the type of Object being stored inside of the e variable is different:
System.Windows.Forms.MouseEventArgs
The bit on the end of all that is what we're interested in: MouseEventArgs. This stands for Mouse Events Arguments. What is being stored inside of the e variable is information the Mouse Event: Did you click a button, if so which one?
The only thing you need to do to detect which button was pressed is to access a property of the evariable. Let's see how to do that.

Which Button was Clicked?

Inside of the Button1_MouseDown Subroutine, type the following code:
If e.Button = MouseButtons.Right Then
MsgBox("Right Button Clicked")
End If
As soon as you type the letter "e", you'll see this pop up box:
Properties and Methods of the Event
To detect which button was clicked, you need the first Property on the list: Button. Double click this property to add it to your code. Then after you typed the equals sign, another pop up list appears. This one:
Select a Mouse Button to detect
This is a list of available buttons that VB can detect. Left and Right are the ones you'll use most often.
When you've added the If Statement, your coding window should look something like this:
VB NET Code for MouseDown Event
When you're finished writing your code, run your programme. Click the button with your Left mouse button and nothing will happen. Click it with the Right mouse button and you should see the message box display.


MouseDown and the Form

Stop your programme. When you are returned to the coding environment, click the down arrow of Button1 at the top of the code. You'll see a drop down box like this:
Form1 Events
Select the one highlighted in the image, "Form1 Events". In the Events box to the right, select MouseDown from the list of available events. A new code stub will appear:
Private Sub Form1_MouseDown( ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown
End Sub
This time, we have a Private Subroutine called Form1_MouseDown. The two arguments are exactly the same as before. The difference is that now this code Handles the MouseDown event for something called MyBase. (This is an object that refers to the code for Public Class Form1.)
The important thing to bear in mind is that we now have a way to detect when a mouse button was clicked on the form itself.
Add the following code inside of Form1_MouseDown:
If e.Button = MouseButtons.Right Then
MsgBox("You clicked on the Form")
End If
The only thing that has changed is the Message Box! The If Statement is exactly the same. Run your programme and test it out. Click anywhere on your Form, and you should see the new message box. However, if you right click on the button, you'll get the old message box. Although the button is on the Form, this is considered a separate control from the Form itself. So it has its own events.
You can detect where on the Form the mouse was when the right mouse button was click. Amend your code for Form1_MouseDown. Change it to this:
Dim xPos As Integer
Dim yPos As Integer
If e.Button = MouseButtons.Right Then
xPos = e.X
yPos = e.Y
MsgBox("The X Position is " & xPos & " The Y Position is " & yPos)
End If
First, we're setting up two integer variable, xPos and yPos. After that we have the same If Statement as before:
If e.Button = MouseButtons.Right Then
End If
Inside of the If Statement, we're using the X and Y properties of the e variable:
xPos = e.X
yPos = e.Y
The X property returns how far across, from left to right, the mouse is; the Y property returns how far down, from top to bottom, the mouse is. These values are assigned to our two variables. The result is displayed in a message box.
When you've wrote the code, run your programme and test it out. Right click anywhere on your form. The new message box should display, telling you where the mouse was when the right button was held down.
Click near the top of the form and you'll see the Y position number go down in value; Click near the bottom of the form and you'll see it go up in value. The very top of the form (or a control) has a Y value of zero.
Click from left to right and you'll see the X numbers go up in value. The very left edge of your form has an X value of zero.

The KeyDown Event in VB .NET

Another useful event is the KeyDown event. As its name suggest, this allows you to detect when a key on the keyboard was held down. This is useful for things like validating text in a textbox.
To test it out, add a textbox to your form. (If you haven't been following the lessons, just start a new project and add a textbox to your new form.). Change the Text property of the textbox to "Press F1 for help." Locate the TabIndex property in the Property Box, and change it to zero. (The Tab Index sets which control is selected when the Tab key is pressed on the keyboard. By specifying zero as the TabIndex property, you're saying that this should be the first control selected.)
Bring up your code window and click the arrow that reveals the list of controls and objects in your project:
Select the Textbox Object
Click on your textbox from the list to select it, as in the image above. Then click the arrow on the Event drop down box to reveal the events available to the textbox. Scroll down and select the KeyDown event:
Select the KeyDown Event
When you select the KeyDown event, a code stub appears:
Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
End Sub
The event that is being Handled is the KeyDown event of TextBox1. Notice, though, that there is a slightly different argument in round brackets (just e As KeyEventArgs in version 2012):
ByVal e As System.Windows.Forms.KeyEventArgs
Again, the variable name is still e. But now we have something called KeyEventArgs on the end. This means that the variable e will hold information about the Key on the keyboard that you're trying to detect.


To see what properties the e variable has available to it, add the following to your TextBox1_KeyDown code:
If e.KeyCode = Keys.F1 Then
TextBox1.Clear()
MsgBox("Help!!!")
End If
As soon as you type the full stop after the letter "e", you'll see this pop up box:
List of Properties and Events for KeyDown
Double click a property to add it to your code. After you type an equals sign, you'll get another pop up box:
Select a Key from the list
The list is a list of keys on your keyboard, some of which you'll have and others that you won't. Scroll down the list until you come to Keys.F1, and double click the item to add it to your code.
The code for the If Statement just clears the textbox and pops up a message.
Try your programme out. Press F1 (If you set TextIndex to zero then the text in the textbox should be selected, and the cursor already flashing. If it's not, click inside of the textbox and then press F1). When the F1 key is pressed, you should see the message box appear.
Another thing you can do is to record the keystrokes a user makes. For example:
Dim RecordText as String
RecordText = RecordText & Chr( e.KeyCode )
MsgBox(RecordText)
The Chr( ) function converts a KeyCode (which is an integer) to its keyboard character.
But try this exercise.

Exercise N

There is an event available to the textbox called Leave. Add another textbox to your form, and write code so that the letters in a postcode are converted to uppercase when the user clicks from your first textbox and into your second textbox.
So your first textbox might read "ts1 4jh". When the user clicks inside textbox2, the text from textbox1 should change to "TS1 4JH". The code can be written in the Leave event of textbox1.

There are an awful lot of Events to explore, and we'll have a look at just one more - the Form Load Event.

The Form Load Event in VB .NET

An important event you'll want to write code for is the Form Load event. You might want to, for example, set the Enabled property of a control to False when a form loads. Or maybe blank out an item on your menu. You can do all this from the Form Load event.
Add another button to your form for this example, and we'll see how the Form Load event works. (If you haven't been folowing along, create a new project and add two buttons to it.
Bring up your coding window, and select the Form1 Events from the drop down box:
Select Form1  Events
In the events drop down box, select Load. A code stub for the Form Load event is then added to your code. Type in the following as the code for the Load Event:
MsgBox("Form Load Event")
Run your programme. You should see the message box display before the Form loads.
To switch off your second Button before the Form loads, add this to your code:
Button2.Enabled = False
Run your programme again. You should see that button is no longer available for clicking on.

We'll now up the pace a bit. We'll have a look at just what Objects are, and how you can create your own.

Comments