|
This
tutorial will be all about Events! After this you will be able to program a
simple game. Basically - from this moment on, you will find programming very
exciting. You will actually be able to program a game with the knowledge of
this, and the previous 6 tutorials. In this tutorial - you will program a
calculator. After this tutorial you will make a simple game.
Introduction
Event handling is a very
important concept in VB.NET. Of course, if you want to learn how to program
games, you have to check for events! A game is basically animation + events.
Let's think about this for a second. If you are programming a game like Mario,
you know that you have to check for certain events, such as - KeyPress, and
Collision Detection. In a game like Tic-Tac-Toe, you have to check weather the
player won or not. Events are relatively simple, its almost like real life -
for every action (event) there's a consequence
(result). For instance, if you press Left then Mario moves Left. So, obviously
in this tutorial we're going to learn how to handle events, and I'm going to
show you how to do that while we program a calculator.
Setting
up your interface
Create a new
Windows Application called "Calculator". Add a large label at the top of
your form. Set its Name property to "Display". Set its Text property
to blank. Set its BorderStyle property to Fixed3D, which gives it a nice
3-dimensional look. Add a GroupBox which has a Text property called "Numbers"
Drag and drop Buttons into the GroupBox. Their text and Name properties are as
follows:
Text | Name
1
btn1
2
btn2
3
btn3
etc...
Create another GroupBox with the text property set to "Operators". Drag and drop Buttons into that,
their Text and Name properties are as follows:
Text | Name
+
Plus
-
Minus
*
Multiply
/
Divide
=
Equals
Your form should look like the image below (you may need to play around with
the sizes of the Buttons, GroupBoxes, Labels, and the Form in order for it to
look exactly like this. It doesn't really matter if it looks the exact
same way, the code is what matters):

Event Handling
Here is where
we learn how to do event handling. There is one important thing to bear in
mind: The letter e stands for Event. Let's take a look at
Form1_KeyDown(Remember, in order to access Form1_KeyDown, you must go to (base
class events) and then go to KeyDown:
Private
Sub Form1_KeyDown(ByVal
sender As
Object,
ByVal e
As System.Windows.Forms.KeyEventArgs)
Handles MyBase.KeyDown
End
Sub
Remember that e
stands for Event, and remember that a lot of things in VB.NET are followed by
a dot. So, in Form1_KeyDown, type in e. (Its kind of hard to explain this in
text, but what I'm trying to say is, type in "e dot") After you type
in the dot, notice that a popup box appears. Select KeyCode from the box; so
it should look like this "e.KeyCode". Now type in = , notice how
another pop-up box appears. The first item is Keys.A, which refers to the A
key on your keyboard. Keys.Left refers to the left arrow key on your keyboard.
The concept is pretty simple, so I don't really need to spend a lot of time on
it (hopefully). If you wanted to tell weather a person pressed the left arrow
key, you would say:
If
e.KeyCode = Keys.Left Then
'Do
what you want when the person presses the left arrow key
End
If
Simple isn't
it? The concept I was trying to teach you, was how to check for events. There
are many ways to check for events. If you put 5 people in a room and ask them
to program a calculator, they would come up with their own ways of doing it.
Some ways are complicated, short, simple, or long; each way of doing it is
based on how a person thinks. The way I teach you to program a calculator may
not be how you think, so I sincerely hope that you will learn to come up with your
own way of doing things.
The Calculator
Finally, we
are going to program our calculator. First things first, as I said before,
there are many ways to make 1 program, and the way I do it may not be very
clear to you. So, I am going to explain how I'm going to code it, before
starting.
In any calculator, you would receive input from the user, then receive an
operator, and then another input, and then the result is displayed. What I'm
going to do is,
a) Take the first input and store it into an integer called Input1
b) When the user presses an operator(+, -, *, or /), store which one it is
into a Boolean. For instance if the user pressed *, then a Boolean called
Multiply would be set to True.
c) Clear the display
d) Take the second input and store it into an Integer called Input2
e) When the user presses =, you check what the Operator is, and you add,
subtract, multiply or divide the numbers.
f) Clear display, and clear variables to get ready for the next operation.
I hope this concept makes sense to you. This is a really simple calculator. It
has no support for decimals and you can only enter 2 numbers in 1
calculation.
The weird
part: Remember that if you want to increase a variable by 1, you would say x =
x + 1. Well, what if you want to add a number to the Display? Lets say
you wanted to make the display 33. You would say Display.Text = Display.Text +
3, right? (in this case you are coding for whenever the user presses 3). When
you click a number, you want to make it so that it adds itself to the display.
Temporarily set Display.Text to 5(in the Form Editor, not in
code). Now double click the 2 button, it will take you to the code, under
btn2_Click. Type this in:
Display.Text =
Display.Text + 2
Run your
program. The Display obviously says 5. Click the 2 Button. See what happens.
It doesn't make it 52! It makes it 7! The reason it does this is because it
(obviously) added 5 and 2 and made it 7. Go back to your code and change
it:
Display.Text =
Display.Text + "2"
Now, it doesn't
add the value 2, it adds the "text" 2, because it is in
"quotes." Run your program, obviously the display still says 5.
Press 2, instead of saying 7, it says 52.
Delete all the code that you made. Make Display.Text(in the form Designer, not
in code) blank. It is now (finally) time to start. The really annoying part:
Coding for all the numbers(0 to 9). The code I'm about to copy and paste will
be fairly large, but I will have an explanation at the end. First things
first, in the declarations area, I declared Input1 and Input2 as Integers. I
declared Add as a Boolean. You have to remember that I only coded for the
number 2, and the + button.
Private
Sub btn2_Click(ByVal
sender As
System.Object, ByVal
e As System.EventArgs)
Handles btn2.Click
Display.Text += "2"
'Line1
End Sub
Private
Sub Plus_Click(ByVal
sender As
System.Object, ByVal
e As
System.EventArgs) Handles
Plus.Click
Input1 = Display.Text
'Line2
Add = True
'Line3
Display.Text = ""
'Line4
End Sub
Private
Sub Equals_Click(ByVal
sender As
System.Object, ByVal
e As
System.EventArgs) Handles
Equals.Click
Input2 = Display.Text
'Line5
If
Add = True
Then
'Line6
MsgBox(Input1
+ Input2) 'Line7
End
If
'Line8
End Sub
The 1st line of
code (well, I mean the code that's not generated for you): Self explanatory,
it adds the number 2 to the Display. The second line of code, as I said
before, you take what's in Display, and you store it into a variable, and
that variable is called Input1. Notice that I do this under the Plus.Click
event. In any calculator, you would take the input only after the user presses
+. The next line of code says "You Are Adding". I'll explain
why you need to set Add to True after a few other explanations. The next line
clears the Display. The line after, stores the input from Display, into a
variable called Input2, notice this happens after you click the Equals sign.
Line 6 checks weather Add is equal to True, and line 7 can only happen when
Add is equal to True. Line 7 is the added result of Input1 and Input2.
Line8 is automatically generated for you after you type Line 6 and hit
enter. It just "ends" the If statement.
Wait a minute! This calculator can only add numbers with 2's! It cant subtract,
multiply or divide either! Ok, I'm sure you get the concept of Line1.
When you click 2, it adds 2 to the display. When you click 3, it has to add 3
to the display too! All you have to do, is instead of using 2, you use 3. For
instance (just for the sake of sorting out confusion), instead of: Display.Text += "2"
in the
btn2.Click event, you would do Display.Text += "3"
in the
btn3.click event. This should be very simple. Just code for all the numbers (0
to 9) Well, by now you have a lot of
code! I repeat, a LOT of code! Well there's a new concept here for you to
learn to day, its called minimizing your code. Take all the
btn0,btn1, all the way up to 9, and click the - button before Private Sub on
each of the number button's click events, that shortens a lot of it. In order
to expand that, you have to click the Plus button ( - is to shorten, and + is
to expand)
The next thing you want to do is, instead of using +, you would want to do
something for -, *, and /. Well its pretty easy! You know how we had a Boolean
declared in the declarations area called Add? Well, declare Subtract as a
Boolean. Now go to the Minus.Click (remember, we are talking about the Button,
Minus) and keep all the code that you had in Add.Click:
Input1 = Display.Text
'Line2
Add = True
'Line3 <- I'm going to change this
for the Minus.Click Event ->
Display.Text = ""
'Line4
Now
instead of Add = True, say Subtract = True.
Input1 = Display.Text
'Line2
Subtract = True
'Line3 <- This is what the
Minus.Click event should look like ->
Display.Text = ""
'Line4
Nothing
changed, the concept is still the same. Now lets move on to Multiply and
Divide; here's where things get a little tricky. Declare a Boolean called
Multiply. Notice how Multiply is underlined! This is because we already have
an object called Multiply! This object is the Multiply Button that you had!
You cant declare or create an object (such as a button) with the same name as
another variable or an object. In this case, the Multiply Boolean that you
Dimmed, is conflicting with the name of the Button you created. So go to your
Multiply Button, and change its name to btnMultiply - this way we know that
its a button. I would suggest you do the same for Divide (change it to
btnDivide). I would recommend that you change the Plus and Minus button
names to btnPlus and btnMinus, respectively. The reason why this didn't
happen with Plus and Minus was, the Boolean name for btnPlus was Add - and was
in no way similar to "Plus." With btnMinus, we declared Subtract as
our Boolean name. The prefix for Button (btn), was made by a man who wanted to
make distinctions for objects simpler. I did not make this up, so if you don't
like these names, talk to that man ^_^. He made up all sorts of prefixes for
object names! Right now this is getting complicated. I did this because
I wanted to show you that names such as MyButton and Add and such aren't very
great names. Rename all your variables and buttons as such: (Notice how the
prefix for Boolean is bln). Go to the Equals event and rename the line that says
If
Add = True
Then; change
it to If
blnAdd = True
Then
Boolean
| Button
blnAdd
btnPlus
blnSubtract btnSubtract
blnMultiply btnMultiply
blnDivide
blnDivide
(Note: the Boolean's name is blnAdd but the Button name is btnPlus, you can
change it if you want; I just did this for demonstration purposes only)
Note: VB.NET automatically changes the function names if you change them in
the Form Designer: Originally it was
Private
Sub Plus_Click(ByVal
sender As
System.Object, ByVal
e As
System.EventArgs) Handles
Plus.Click '<--look
at this line
VB.NET
automatically changed it to
Private
Sub Plus_Click(ByVal
sender As
System.Object, ByVal
e As
System.EventArgs) Handles
btnPlus.Click '<--look
at this line
But
what about the Plus_Click (The third "word")? That doesn't really matter, you could change that
name if you want, its just there for your convenience.
Back to the btnMultiply: Change it like you did with btnSubtract (except,
obvisouly, use btnMultiply instead of Subtract). As for btnDivide: Do the same
for Divide. Make sure you change the code that says blnAdd = True, to
blnSubtract = True or blnMultiply = True or blnDivide = True
But now you have to change the code for the Equals event. Its relatively simple.
All you have to do is add:
If
blnAdd = True
Then
MsgBox(Input1
+ Input2)
End
If
If
blnSubtract = True
Then
MsgBox(Input1 -
Input2)
End
If
If
blnMultiply = True
Then
MsgBox(Input1 *
Input2)
End
If
If
blnDivide = True
Then
MsgBox(Input1 /
Input2)
End
If
Simple right? Now the only tricky part is clearing all the values to
false. All you have to do is, at the end of the Equals.Click event, type this
in:
blnAdd = False
blnSubtract = False
blnMultiply = False
blnDivide = False
Display.Text = ""
The reason why you have to do this is because, well, you are creating a new
problem! You want to clear the display, and "stop" adding and subtracting
and multiplying and dividing. If we didn't do this, what would happen is, lets
say we first multiplied. Multiply is set to True. but let's say you decided to
add next. Well, when you hit equals, Multiply and Add are still True, so you
would get 2 MessageBoxes saying the product and the sum! The reason behind this
is because, just because you set Add to true, doesn't mean multiply is
automatically set to false!
Run your program, you now have made a calculator!
The Source Code
for this tutorial is located here:
You can also
locate this by logging in to vbProgramming Forums and going to:
Tutorials > Tutorial Source Code > Source Code
|
|