[go: up one dir, main page]

0% found this document useful (0 votes)
9 views44 pages

Write Your First Visual Basic Program: Lesson 1

This document serves as an introductory guide to Visual Basic programming, highlighting its ease of use for developing Windows applications and games. It outlines the advantages and disadvantages of Visual Basic, provides step-by-step instructions for creating a simple program, and explains fundamental concepts such as properties, controls, events, and variables. The document concludes with examples of programming events and using variables to store data.

Uploaded by

lsbexcel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views44 pages

Write Your First Visual Basic Program: Lesson 1

This document serves as an introductory guide to Visual Basic programming, highlighting its ease of use for developing Windows applications and games. It outlines the advantages and disadvantages of Visual Basic, provides step-by-step instructions for creating a simple program, and explains fundamental concepts such as properties, controls, events, and variables. The document concludes with examples of programming events and using variables to store data.

Uploaded by

lsbexcel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 44

Write Your First Visual Basic Program

Lesson 1
What Is Visual Basic and Why do I need it?
Visual Basic is Easy to learn Programming language.
With Visual Basic you can develop Windows based applications and games.
Visual Basic is much more easier to learn than other language (like Visual C++),
and yet it's powerful programming language.

Visual Basic suit more for application developing than for Games developing.
You can create sophisticated games using Visual Basic, But
If you want to make a really advanced professional game like Quake 2,
You may choose other language (like C++), that would be much more
harder to program with.
However, Visual Basic will be probably powerful enough to suit all your application
and games programming needs.

The advantages of Visual Basic:


1) It's simple language. Things that may be difficult to program with other language,
Can be done in Visual Basic very easily.
2) Because Visual Basic is so popular, There are many good resources (Books,
Web sites, News groups and more) that can help you learn the language.
You can find the answers to your programming problems much more easily
than other programming languages.
3) You can find many tools (Sharewares and Freewares) on the internet that will
Spare you some programming time.
For example, if you want to ping a user over the internet in your program,
Instead of writing the ping function yourself, you can download a control
that does it, and use it in your program.
Compare to other languages, Visual Basic have the widest variety of tools
that you can download on the internet and use in your programs.

The disadvantages of Visual Basic:


1) Visual Basic is powerful language, but it's not suit for programming really
sophisticated games.
2) It's much more slower than other langauges.

Getting Started
Note that all the images in this tutorial taken from Visual Basic version 6.0.
If you using other version of Visual Basic, the images that you will see may
be a little different.

Run the Visual Basic program. The first thing you see is:

Figure 1
Here you choose what is the kind of the program you want to create.
For creating a simple Visual Basic program, choose the Standard EXE,
and press the Open Button.

(If Figure 1 is not the first thing you see when you run Visual Basic,
choose from the Visual Basic menu File->New Project (Figure 2))

Figure 2
After you've clicked the Open button, you will see:

Figure 3
Look at the form with the title bar Form1.
This is how your program will look like.
Everything you will place on this form will appear in your program.
As you can see, your form is currently empty.
You didn't program anything yet, but lets run the program!

Click on the Play button in the toolbar (Figure 4)

Figure 4

Now your program is running (Figure 5):

Figure 5

As you can see, the form is empty.


You can move the form, minimize and maximize it.

To stop the program from running, you can click on the Stop button
in the Toolbar (Figure 6), or click the form's X button (Figure 7).
It's very recommended that you will always close your programs using the
form's X button instead of the Visual Basic Stop button.
It's like shutting Windows From the Start button, instead of Pressing
the Power button.

Figure 6

Figure 7

Back Forward

Learning about Properties


Every component (form is component for example) has properties,
that determine its look and its functioning.
Properties can be the component color, width, height and more.

To see the form properties, select from the menu View->Properties Window (Figure
8).

Figure 8
The properties window looks like this:

Figure 9
In the red circle you can see the component name:
These are the properties of a Form, and the form's name is Form1.

The column marked by the blue circle contains the form's properties names:
The form has Name property, Appearance property AutoRedraw property, and more.

The column marked by the black circle contains the form's properties values:
The form's Name is Form1, The form's Appearance property is 1 - 3D, and so on.

You can change the form's properties.


For example, lets change the form's Caption property.
What is the Caption property? The Caption is the text that appears on the
Form's title bar.
Right now the text that appears on the form's title bar is Form1 (Figure 5).

To change the Caption property, simply click on the Caption property in the
form's properties names column (Figure 10).

Figure 10

As you see, the current Caption is Form1.


Delete the "Form1" text and type instead of it "Hello" (Figure 11).

Figure 11
Now run the program using the Play button (Figure 4).
You will see that the text on the form's Title bar is Hello (Figure 12).

Figure 12

Try to change others properties:


Change the form's BackColor property to change the form's background color,
Change the Icon property to change the icon that appears on the form's title bar.
You can try and change every property, and in this way learn what does it do.

Adding Controls to the Form


There are many controls you can use with your program:
Buttons, Text Boxes, Pictures, Scroll Bars and more.
You can see all these controls in the Toolbox.
To see the Toolbox, Select from the menu View->Toolbox (Figure 13).

Figure 13
And you will see the Toolbox (Figure 14):

Figure 14
Now lets add a button to your form.
Buttons in Visual Basic called "Command Buttons".
To add a button, click on the Command Button icon in the Toolbox (Figure 15).

Figure 15

As results, the Command Button icon will look pressed (Figure 16).

Figure 16
Now click on the form with the left mouse button, and hold the button
down while moving the cursor.
You will see a rectangle.
Release the mouse button, and in the place of the rectangle you
will see a button (Figure 17).

Figure 17

Changing the button's Properties


Now you have a button on your form.
You can change its location by dragging it, and change its
size by dragging the Blue Hot Spots that found on each one of its conrners.

Run the program by clicking the Play button.


You can see that you have a button on your form, that you can click on it,
But it still doesn't do anything.

To see the Command Button's Properties window, click on it with


the right mouse button and select Properties for the pop-up menu (Figure 18).

Figure 18
The Command Button's Properties window (Figure 19):

Figure 19

As you can see, In the top of the properties window, right under the title bar,
appears "Command1 CommandButton".

Command1 - because it's the name of this specific Command Button (look
at the name property).

CommandButton - because this is this component type.

Note that two components can't have the same name.


If you will add another Command Button to your form, its name will
be "Command2" by default.
If you want you can change the Name of any component, by simply
changing the component's Name property.

Now lets change the Command Button's Caption property.


The caption property is the text that appears on the Command Button.
Change the Caption property to "Click Here", and you will see that
"Click Here" appears on your Command Button.

Change the Command Button's BackColor property to blue (or other color).
The change won't take affect, untill you will set the Command Button's Style
property to 1 -Graphical.

You can now play a little bit with the Command Button's properties,
this is the best way to learn what every property does.
You can also add other controls from the Toolbox to your form,
And play around with their properties.

Learning about Events


Visual Basic is "Event Driven" language.
What does it mean?

Everything that happening, launch an event.


You've moved the mouse? The "MouseMove" event has been launched.
You've pressed a key? The "KeyPress" event has been launched.

You can program the events.


When the mouse moves, you can change the Form's color (for example),
and when a key is pressed, You can play a MP3 file.

To start programming the events, double click on the form.


You will see the "Code Window" (Figure 20).

Figure 20

The Code Window opened with the Form_Load event.


The Form_Load event occurs when the form is loaded, and this happening
when you start the program.
So the code that you will enter to the Form_Load event will be launched
when the program is being started.
The code that belongs to the Form_Load event should be placed
between Private Sub Form_Load() and End Sub

The Form_Load event should look like this:

Private Sub Form_Load() (The beginning of the Form_Load event)


This is the code that belongs to the Form_Load event
End Sub (The end of the Form_Load event)

Lets program the Form_Load event.

"MsgBox" is Visual Basic command that launch a message box.


for example, the line:

MsgBox "Hello"

Will launch a message box with the text "Hello".

Insert the line MsgBox "Hello" to the Form_Load event (Figure 21).

Figure 21

Now run your program using the Play button.


When the program is started, a message box with the
text "Hello" is appear (Figure 22).

Figure 22
More Events
The Form has more events besides the Form_Load event.
How can you find them?

Click on the Drop-Down List that found in the upper left corner of
the Code Window, where appears right now the text "Form" (Figure 23).

Figure 23

You will see a list of the components that found in your program.
You have 1 command button with the name "Command1" and 1 Form.
Here you select which component's event you want to program.
We want to program a form's event, so select "Form" from the list (Figure 23).

Which events the form has?


Click on the Drop-Down List that found in the upper right corner of
the Code Window, where appears right now the text "Load" (Figure 24).

Figure 24
You will see the complete list of the form's events:
Load, LostFocus, MouseDown, MouseMove and more.

Lets program the Form_Unload event.


Select "Unload" from the form's events list.
The Form_Unload event occurs when the form is being unloaded,
and this happening when you close the program (Using the form's X button (Figure
7)).
So the code that you will write in the Form_Unload event will be launched
when you close the program.

Insert the following line to the Form_Unload event:

MsgBox "GoodBye"

After you've inserted this line to your Form_Unload event,


the Form_Unload event should look like this:

Private Sub Form_Unload(Cancel As Integer)


MsgBox "GoodBye"
End Sub

Run the program.


When the form is being loaded at the very start, The Form_Load event
is being executed and a message box with "Hello" text is popping.
When you close the program by clicking the form's X button, the Form_Unload
event is being executed and a message box with "GoodBye" text is popping.

The Command Button's Events


Now lets program some of the Command Button's events.
Select "Command1" from the components list (Figure 23).
Check which events the Command Button has by clicking
the Events list (Figure 24).
We want to execute a code when the user is clicking on the button,
So lets program the Command Button's Click event.
Select "Click" from the Events list.
Insert the following line to the Click event:

MsgBox "You have Clicked on the button!"

After you inserted this line to the Click event the Click event should look like this:

Private Sub Command1_Click()


MsgBox "You have Clicked on the button!"
End Sub

As you can see, the Command Button's Click event called "Command1_Click",
because the name of the specific Command Button that we program
its Click event is "Command1".
If we had program the Click event of a Command Button with the
name "BlahBlah7", the Click event would be called "BlahBlah7_Click".
Every component has its own unique events, therefore if you had
5 Command Buttons on your form, every one of them has its
own unique Click event.

Run the program, and click the button.


When you clicking the Command Button with the
name "Command1", The Command1_Click event is being
executed, and a message box with the text "You have Clicked on the button!"
is popping.

The Command Button's Events (Continue)


To learn about more events, we will use the "Print" command.
The "Print" command simply writing a text on the form.
For example, the following line:

Print "Hello"

Will write "Hello" on the form (Figure 25)

Figure 25
Add another Command Button to your form.
The New Command Button's name is "Command2" by default (Figure 26)

Figure 26

Now, rewrite the Command1 Click event and insert the


following line to it:

Print "This is Command1"

Select "Command2" (This is the name of the second


Command Button) from the Components list (Figure 23),
And select "Click" from the Command2 events List.

Enter the following line to the Command2_Click event:

Print "This is Command2"

After you've done so, your code should look like this:
Private Sub Command1_Click()
Print "This is Command1"
End Sub

Private Sub Command2_Click()


Print "This is Command2"
End Sub

Run the program.


When you are clicking on Command1 Button, the text "This is Command1"
appears on the form, and when you are clicking on Command2 Button,
the text "This is Command2" appears on the form.

Lesson 2
Learning about Variables
Using Variables is one of the most basic and important subjects
in programming, so this lesson is very important.

Variables are destined to save data.


You can save in variable Text or number.
For example, you can have one variable that holds the Text "Hello and Goodbye",
and have another variable that holds the number 623882

You can think about variables as a cabinet's drawers.


Every drawer has a sticker on it with its unique name.
You can put in each one of the drawers one number or one text String.
During your program, you can open the drawer with the sticker "TheUserName"
and get the text string that found inside the drawer.
You can also delete the text string that found inside the drawer
and put instead of it other text string.

Right now, we are going learn about 2 variable types.


The first type called Integer.
Integer variable can store an Integer number (round number without any fraction)
between -32,768 to 32,767.

You can store in Integer variable the number 0 or the number 375 or
the number -46, but you can't store the number 4.5 (Because of the .5)
or the number 100,000 (Because It's bigger than 32767) or the
number -50,042 (Because it's smaller than -32,768)

The second type called String.


You can store in String variable any text that you want.
For example "Hello" or "abcDDefGhIjk123456 blah blah %$#@!???

Working With Integers


The process of creating variable called "Declaring"
To Declare (=create) Integer variable simply write:

Dim MyTest As Integer

What does the line above do?


It creates an Integer variable with the name MyTest.

Dim = Declare
MyTest = the name of the new variable
As Integer = The new variable type will be Integer.

Now you can put a number inside this variable.


You can do that by simple write:

MyTest = 10

The line above will insert the number 10 into the MyTest variable.
Now the MyTest variable stores the Number 10, but how
can you access this value from your program?
You can do that using the variable name. Example:

Print MyTest

The line above will write 10 on the form.


Pay attention to the differents between

Print MyTest

and

Print "MyTest"

Where you putting a text inside quotes (Like in the bottom line),
Visual Basic treat it as a Text, and will print it As-Is.
The Print "MyTest" Line will print MyTest on the form.

Where you putting a text Without quotes (Like in the upper line),
Visual Basic treat it as a variable name, and will print the value that found
in the variable.
The Print MyTest Line will print the value that found in
the MyTest variable, therefore it will print 10 on the form.

Question: What will be printed on the form


after executing the following code:

Dim Blah As Integer


Print Blah
Blah = 10
Blah = 20
Print Blah
Blah = 30
Print "Blah"
Print Blah

After you've thinking about the answer, you can


check it by inserting the code above into a Command Button's
Click event, and press the button at run-time.

Anyway, the Answer can be found on the next page...

Answer:

0
20
Blah
30

Why is that?
Lets pass over the code line after line:

Dim Blah As Integer


A new Integer with the name Blah has been declared
Print Blah
Will print the Value that found in the Blah variable.
But there is nothing in the Blah variable!
The Blah variable has just been declared, and we
didn't put inside it any value yet.
The default value of any integer variable is 0.
When you write :
Dim Blah As Integer
It's like you've written:
Dim Blah As Integer
Blah = 0

So it will print the value that found right now


in the Blah variable - 0

Blah = 10
Now the Blah variable holds the number 10

Blah = 20
Now the Blah variable holds the number 20
What's happened to the 10 that was inside it?
It has been deleted!
A variable can holds only one value, and when
you put in it a value, the old value is being immediately deleted.

So what is the differents between

Blah = 20

and

Blah = 10
Blah = 20

There is no differents!
In both cases the Blah variable will hold the number 20

Print Blah
Will print the value that found right now
in the Blah variable - 20

Blah = 30
Now the Blah variable holds the number 30

Print "Blah"
Will print the Text that found between the quotes - Blah

Print Blah
Will print the value that found right now
in the Blah variable – 30

Question: What will be printed on the form


after executing the following code:

Dim Blah As Integer


Blah = 2
Print 2 + 3
Print "2 + 3"
Print Blah + 3
Print Blah
Blah = Blah + 1
Print Blah
Blah = Blah + Blah
Print Blah

Answer:

5
2+3
5
2
3
6

Why is that?
Lets pass over the code line after line:

Dim Blah As Integer


A new Integer with the name Blah has been declared

Blah = 2
Now Blah holds the value 2

Print 2 + 3
When you execute command (the Print command in the case)
on expression, Visual Basic will evaluate the expression first,
and then will execute the command on the evaluation result.

In this case we execute the command Print on the expression 2 + 3.


The expression will be evaluated: 2 + 3 = 5.
The evaluation result is 5, and then Visual Basic will
execute the command Print 5
So in other words, Print 2 + 3 is equivalent to Print 5
after executing the Command Print 5 , 5 is been printed on the form.

Print "2 + 3"


As I said before, Everything that found inside quotes is being
treated as a string. So the string 2 + 3 will be printed on the form.
Print 2 + 3 will print the value of the expression 2 + 3,
Print "2 + 3" will print the text string 2 + 3
Print Blah + 3
Now the expression is Blah + 3.
when a variable is found inside expression, it's being
replaced with its value.
In this case the value of the variable Blah is 2.
So the Blah in the expression is being replaced with 2.
After the replacement the new command is Print 2 + 3
As we saw earlier, after executing this command
the value 5 will be printed on the form.

Print Blah
Will replace the Blah with its value.
Because the Blah value is 2, After the replacement
the new command will be Print 2
After executing this command, the value 2
will be printed on the form.

Blah = Blah + 1
The line above simply says:
Put in the Blah variable, the value of the expression Blah + 1
The computer is first evaluate the expression Blah + 1
Blah is being replaced with its value: 2.
After the replacement the computer evaluates the expression 2 + 1.
The expression value is 3.
So now, after the "Blah + 1" expression evaluation,
the command is: Blah = 3
As you know by now, this command will
put the value 3 in the Blah variable.
Summary:
After executing the command Blah = Blah + 1,
the value 3 will be inserted into the Blah variable.

Print Blah
Will replace the Blah variable with its value: 3.
So the command that will be eventually executed is Print 3

Blah = Blah + Blah


Will Put in the Blah variable, the value of the expression Blah + Blah
The computer is first evaluate the expression Blah + Blah
Blah is being replaced with its value: 3.
After the replacement the computer evaluates the expression 3 + 3.
The expression value is 6.
So now, after the "Blah + Blah" expression evaluation,
the command is: Blah = 6
After executing the command Blah = 6,
the value 6 is being inserted into the Blah variable.

Print Blah
Will replace the Blah variable with its value: 6.
So the command that will be eventually executed is Print 6

More Complicated Expressions


You can use the following operators in expressions:
+ Plus
- Minus
* Multiply
/ Division
( Openning parenthesis
) Closing parenthesis
^ Power

For example, this is a valid expression:


(Blah + 5) * MySecondVariable - (4 + 10 / Blah)

The order of the operators are like in math:


First "(" and ")" , then "^", then "*" and "/", and at last "+" and "-"

For example:
2 + 3 * 4 is equal to 14
(2 + 3) * 4 is equal to 20

More Variable Types


What will be printed on the form after
executing the following code?

Dim ABC As Integer


ABC = 4.8
Print ABC

Answer:
The Integer variable can't store a number with fraction,
So the computer will round the 4.8 to 5, and will
Insert 5 to the ABC variable.
So the Command Print ABC will print 5 on the form.

So how can you store a number with fraction in a variable?


For this purpose you have other variable types that can
store round numbers like the Integer type, and in addition can
store numbers with fractions.

The Variable types list:

Byte - Can store only Integer numbers between 0 to 255

Integer - Can store only Integer numbers between -32,768 to 32,767

Long - Can store only Integer numbers between -2,147,483,648 to 2,147,483,647

Single - Can store Non-Integer (numbers with fractions) Numbers


between -3.402823E38 to -1.401298E-45 for negative values,
and 1.401298E-45 to 3.402823E38 for positive values.

Double - Can store Non-Integer Numbers between


-1.79769313486231E308 to -4.94065645841247E-324 for negative values,
and 4.94065645841247E-324 to 1.79769313486232E308 for positive values
Why would I use Byte variable that can store Integer numbers
between 0 to 255, while I can use Integer variable that can store
numbers between -32,768 to 32,767?

The Answer is: Because the Byte variable is taking less memory.

So if you have variable that will not store numbers


greater than 255 or less than 0, declare it as Byte variable
and save a little amount of memory.

If you need to store Non-Integer numbers in variable,


declare it as Single or as Double.

The Declaring command is very simple:

Dim Abc As Double


Dim Blah As Single
Dim Popeye As Byte

And so on.

Working With Strings


String variables are meant to store Text.
When you assign a text to a String variable,
you must put the text inside quotes.

For example:

Dim Abc As String


Abc = "Good Morning"

Question: What will be printed on the


form after executing the following code?

Dim kuku As String


kuku = "Hello!!!"
Print "kuku"
Print kuku

Answer:

kuku
Hello!!!

Why is that? Lets pass over the code line after line:

Dim kuku As String


Will create a new String variable

kuku = "Hello!!!"
Now the kuku variable holds the text Hello!!!
Print "kuku"
Everything that found inside quotes is being treated as text String,
So it will print kuku on the form.
The computer Is NOT associate the text "kuku" with
the variable kuku, because of the quotes.

Print kuku
Will replace the kuku with its value (Hello!!!),
and after the replacement will execute the new command Print "Hello!!!"

You can join two Strings together using the "+" operator.
Example:

Dim gogo As String


Dim popo As String
gogo = "Hello"
popo = "world"
gogo = gogo + " !!! " + popo
Print gogo

The code below will print Hello !!! world on the form.
The expression gogo + " !!! " + popo is equal to
Hello + " !!! " + world and that's equal to "Hello !!! world"
So eventually, the command that will be executed is gogo = "Hello !!! world"

Scope of Variables
Insert two Command Buttons to your form (with
the names Command1 and Command2),
and Add the following code to your program:

Private Sub Command1_Click()


Dim gogo As Integer
gogo = 100
End Sub

Private Sub Command2_Click()


MsgBox gogo
End Sub

Run the program, and click on the Command1 button.


the code that found in the Command1_Click event will be executed.
The gogo variable will be declared, and it will store the value 10.

Now press on the Command2 button.


In result, the MsgBox gogo Line will be executed.
But instead of displaying the value of the gogo variable (100),
It shows nothing, like if the gogo variable hasn't been declared at all!

The reason for all of this, is the scope of the variable.


Every variable that been declared, "Exist" only in the
Sub or function that he was declared in.

What is Sub? (We will learn about functions later)


Sub is a Block of code that starts with Sub and
ends with End Sub
Every event is a sub, because it begins with Sub and
ends with End Sub

For Example:

Private Sub Command1_Click()


MsgBox "Hello"
End Sub

Every line of code that found between the Sub Command1_Click()


and the End Sub is belong to the sub Command1_Click()

So because we've declared the gogo variable in the


Commad1_Click event, it's declared only within the sub, and
it's not declared in the Command2_Click event.

So if you want that a specific variable will be "exist" in


your whole program, no matter from which sub you call it,
what can you do?
The Answer is in the next page...

As you saw in the previous page,


If you declare variable in a sub, it exist only
within the sub.

To declare variable that will be exist in all subs,


you have to declare it in the "Declarations area" of your code.
Choose "(General)" From the components List in the code window (Figure 1).

Figure 1

Put the gogo declaration statement in the "Declarations area".


Simply write:

Dim gogo As Integer


And delete the old statement that found
in the Command1_Click event.

After you've done so, your code should look like this:

Dim gogo As Integer

Private Sub Command1_Click()


gogo = 100
End Sub

Private Sub Command2_Click()


MsgBox gogo
End Sub

Now the gogo variable is being declared in the Declarations area


of your code, and should be available from every part of your code.

Lets check it out:


Run the program.
The gogo variable is being declared immediately when the
program is being started.

Press the Command2 Button.


A message box with the number 0 is popping.
It is because the gogo variable has been declared, but
we didn't assign any value to it yet, so right now its value
is the default value - 0.

Press the Command1 Button.


The value 100 is being assigned to the gogo variable.

Press the Command2 Button - a message box


with the value 100 is popping.

Choosing A Valid Name For Variable


When declaring on variable, you choose its name.
For example:

Dim Tuti As Integer

The example above will set the variable


name to be "Tuti".
The names you choose for your variables don't have
to have any meaning, but still there are some limitations
about the names you can call your variables.

The Rules:

1)The only characters that can appear in the name are


letters, numbers and the character _ (the underscore character)
You can't use other characters like: ` ! @ # % ^ & * ( )
Therefore, the following names are NOT valid: AB!, BB$, tot#o
2)The Name Must begin with a letter: You can't
use the names: 2abc, 3, 2345, _aba

3)You can't use space in the variable's name.


Therefore, the following names are NOT valid: A B, hello world

4)You can't call your variable with a name that is a Visual Basic
Command or Function (these names are been called "saved names").
For example you can't use the name Print, because there is
command in Visual Basic that called Print (which we used pretty much
in this tutorial).
You can know easily if a name is a saved name by typing it anywhere
in your code. All the saved names are being painted with blue color.
Few examples for saved names: Print, Sub, End, MsgBox

Examples for valid names:


a, A, AaAaA, aBhguKJhUJYf, abc123, abc123abc123, hello_world123

There is much more to learn about variables, like constants,


booleans, arrays and more.
What you've learnt by now is necessary for continuing
with the next lessons.
More advanced variables subjects will appear
during the next lessons.

Lesson 3
The Command Button's KeyPress, KeyDown and KeyUp Events
The events that will be mentioned in the following pages
are commonly used, and without learning about them
you really can't go anywhere in Visual Basic programming.

To try these examples, start a new project (as being


taught in Lesson 1).

Add 1 Command Button to your form. The Command


Button is called by default Command1.

Copy the following code to the code window (you


can copy and paste it using Ctrl + C for copying
and Ctrl + V for pasting):

Private Sub Command1_KeyDown(KeyCode As Integer, Shift As Integer)


Print "KeyDown"
End Sub
Private Sub Command1_KeyPress(KeyAscii As Integer)
Print "KeyPress"
End Sub

Private Sub Command1_KeyUp(KeyCode As Integer, Shift As Integer)


Print "KeyUp"
End Sub

When the Command Button's KeyDown event will be executed,


"KeyDown" will be printed on the form,
When the Command Button's KeyPress event will be executed,
"KeyPress" will be printed on the form, and when
the Command Button's KeyUp event will be executed,
"KeyUp" will be printed on the form.

Run the program, and click the button with the mouse.
Nothing has happened.
It's because the KeyDown, Key_Press, and KeyUp events are
being executed Only when you press a key on the keyboard.

Now press any key on the keyboard, hold it down for few seconds,
and then release it.
Your form will look like this:

Figure 1

Lets see:
The first event that been executed is the KeyDown event,
because "KeyDown" was the first text that been printed on the form.

The second event was KeyPress, and then again KeyDown.


After every KeyDown event that been executed, a KeyPress
event had been executed.

We learnt that when a key is being holded down, the


KeyDown and the KeyPress events are being executed in
this order over and over again, until the key is up again.

When you release the key, the KeyUp event is being executed once.

Learning about Parameters


Parameters are variables that being passed to a Sub.

Look at the first line of the Command Button's Click event:

Private Sub Command1_Click()

And at the first line of the Command Button's KeyPress event:

Private Sub Command1_KeyPress(KeyAscii As Integer)

The Click event's first line is ended with


empty parentheses () and the KeyPress event's first
line is ended with (KeyAscii As Integer)

What is the (KeyAscii As Integer) ?


It's a parameter that been passed to the KeyPress event.

This parameter is an Integer variable with the name KeyAscii.


Like if you've declared Dim KeyAscii As Integer

Why do we need this variable?


Because its value is very useful.

The KeyPress event is being executed when the user


press a key, and This variable holds the Ascii value of the
key that been pressed.
With This Ascii value you can know on which key
the user has pressed.

For example, the Ascii value of the "A" character is 65.


If the user has pressed the key "A" on the keyboard,
The KeyAscii parameter value will be 65.

Lets see an example.


Insert the following line to the Command1 KeyPress event:

Private Sub Command1_KeyPress(KeyAscii As Integer)


Print KeyAscii
End Sub

Run the program and press several keys.


You will see the Ascii value of every key you're pressing.
Notice that the KeyAscii values of "A" and "a" are differents.
Every characters has its own KeyAscii value,
and 2 characters that are the same letter, but have different case,
have different KeyAscii value.

More About Ascii


How can I know what is the Ascii value of a specific character?
Use the Asc command.
For example, the following line:

Print Asc("b")

Will print on the form the Ascii value of the character "b".

How can I know which character's Ascii value is 98?


Use the Chr command.
For example, the following line:

Print Chr(98)

Will print on the form the character that its Ascii value is 98.

Look at the first line of the Command Button's KeyDown Event:

Private Sub Command1_KeyDown(KeyCode As Integer, Shift As Integer)

As you can see, the KeyDown event gets two parameters:


The KeyCode parameter, and the Shift parameter, both are
Integer type.

Every Sub can get no parameters (like the Click event), can get
one parameter (like the KeyPress event) or can get more than
one parameter.

If a sub is getting more than one parameter, the parameters


have to be separated with commas.
For example:

Private Sub MySubName (Parameter1 As String, Parameter2 As Integer,


Parameter3 As String)

Lets check out the KeyDown event's parameters.

The first is KeyCode, and it holds the KeyCode value


of the pressed key.
The KeyCode value is usually different from the Ascii Value.

The different between KeyCode and Ascii, is that


every character has Ascii value (for example G, @, |, =, and more)
but there are some keys that don't represent any character, for example:
Alt, F4, Ctrl, The left arrow key.

These keys don't have Ascii value, but they have KeyCode value.
For example, the KeyCode value of the Ctrl Key is 17.
Ascii represent characters, while KeyCode represent Keyboard's keys.
Because of that, the characters "a" and "A" have different Ascii value,
but they have the same KeyCode value, because the same key
is typing "a" and "A".

The second parameter is Shift, and its value helps you


to determine if the user has pressed the Shift, Ctrl or Alt keys.
The Shift holds the value 1 if the user has pressed the Shift key,
the value 2 if the user has pressed the Ctrl Key,
and the value 4 if the user has pressed the Alt Key.

If the user has pressed the Alt key and the Shift key together,
the Shift value will be 4 (for the Alt key) + 1 (for the Shift key) = 5

Examples:

If the user has pressed the "A" key,


The KeyCode parameter will hold the number 65, and
the Shift parameter will hold the value 0.

If the user has pressed Shift and "A" together,


The KeyCode parameter will hold the number 65, and
the Shift parameter will hold the value 1.

The KeyUp event's parameters are the same as the KeyDown event's parameters.

MouseMove, MouseDown and MouseUp Events


Lets check out the Command Button's MouseMove,
MouseDown and MouseUp events.

We will do that like we've done before,


by inserting different Print commands to every event.

Copy the following code to your program:

Private Sub Command1_MouseDown(Button As Integer, Shift As Integer, X As


Single, Y As Single)
Print "MouseDown"
End Sub

Private Sub Command1_MouseMove(Button As Integer, Shift As Integer, X As


Single, Y As Single)
Print "MouseMove"
End Sub

Private Sub Command1_MouseUp(Button As Integer, Shift As Integer, X As


Single, Y As Single)
Print "MouseUp"
End Sub
Run the program.
Move the mouse over the form - nothing is happening.
Move the mouse over the Button - The Button's MouseMove event
is being executed every time you move the mouse over it, therefore
you see that "MouseMove" is being printed on the form
every time you move your mouse over the button.

Click on one of the mouse buttons when the mouse is over the button,
and hold the button down.
The MouseDown event is being executed.
Release the button, and the MouseUp event is being executed.

MouseMove, MouseDown and MouseUp Events (Continue)


Lets check out these events parameters.

Private Sub Command1_MouseDown(Button As Integer, Shift As Integer, X As


Single, Y As Single)

Each one of these events gets the same parameters:


Button, Shift, X and Y.

The Shift parameter is the same as the KeyDown


event's Shift paramater.

For example, if you'll press the Shift button while clicking


the mouse, the Shift value will be 1.

The Button parameter value is 1 if you've clicked


the left mouse button, and 2 if you've clicked the
right one.

The X and Y parameters are the X and Y coordinates of


the mouse cursor, relative to the upper left button corner.
The coordinates of the upper left button corner are (0, 0)
The coordinates of the Bottom Right button corner are (Button Width, Button Height)

You can try a little example.


Put the following line in the Command Button's MouseMove event:

Print X, Y

This line will print the X coordinate, and next to it


the Y coordinates (For example, the line:
Print "Hello", "World"
will print: Hello World).

Additional Command Button's Properties


Add 1 Command Button to your form,
and change the following properties to
see what they do.

Caption - the text that appear on the button

Font - The Caption's font (Figure 2).

Figure 2

ToolTipText - Insert into this property the text


that will appear when the mouse is stand still
on the button (Figure 3).

Figure 3

Enabled - Setting this property to "False" will make


the button be gray, and the user will no be able to press on it (Figure 4).

Figure 4
BackColor - This is the background color of the button (Figure 5).
This property will take affect only after you will set the
Button's Style property to 1 - Graphical

Figure 5

Picture - The Picture that appear on the button (Figure 6).


This property and all the following Picture related properties will
take affect only after you will set the
Button's Style property to 1 - Graphical

Figure 6
DisabledPicture - The Picture that will appear on the button when
it disabled (When the Enabled property is "False", like in Figure 4).

DownPicture - The Picture that will appear on the button when


the button is being pressed.

Visible - If you will set this property to "False", the Button


will not appear on your form at run-time.

MousePointer - Choose here the mouse pointer (Arrow, Hourglass, and more)
when it will be over the button.
If you will set the property to be 99-Custom,
The mouse pointer will be the icon that you will select in the MouseIcon property.

Left - The Button X coordinate, relative to the form left border.

Top - The Button Y coordinate, relative to the form Top border.

Width - The Button width.

Height - The Button height.

Additional Form's Properties


The Form has many of the Command Button's properties
(MousePointer, BackColor, Visible and more).
He also has additional properties:

Caption - The text that appear in the Form's title bar,


and in the taskbar.

Icon - The Icon that appear in the form's title bar (Figure 7)
and in the Task bar (Figure 8).

Figure 7

Figure 8
ControlBox - Set this property to "False" to remove
the title bar's Close, Minimize and Maximize buttons (Figure 9).

Figure 9

MaxButton - Set this property to "False" to disable


The title bar Maximize Button.

MinButton - Set this property to "False" to disable


The title bar Minimize Button.

ShowInTaskbar - Setting this property to "False" will


cause the form not showing in the task bar.

WindowState - The initial appearance style of the form:


Minimized, Maximized, or normal.

The Form's KeyPreview Property


To understand this property,
lets look on the following example:

Start new project, and add 1 Command Button


(named Command1) to your form.
verify that the Form's KeyPreview property is set to "False".
Add the following code to your program:

Private Sub Command1_KeyPress(KeyAscii As Integer)


Print "Button Pressed"
End Sub

Private Sub Form_KeyPress(KeyAscii As Integer)


Print "Form Pressed"
End Sub
The code above will print "Button Pressed" on
the form when the Command Button's KeyPress event
will be executed, and print "Form Pressed" when the
Form's KeyPress event will be executed.

Run the program and press any key on the keyboard.


"Button Pressed" is appearing on the form, but
"Form Pressed" isn't appearing.

The Form's KeyPress event hasn't been executed.

When the KeyPreview property is "False",


if any control is found on the form (the command button in this case),
It will get all the Key events (KeyPress, KeyDown and KeyUp)
instead of the form.

To allow the Form's Key events be executed,


set the KeyPreview property to "True".

Lets try it. Set the KeyPreview


property to "True", run the program again
and press any key.
The Form's KeyPress event has been executed,
in addition to the Button's KeyPress event that
been executed too.

Notice That the form's KeyPress event executed


before the Button's event.

Setting Properties At Run-Time


By now you know how to set a component
property before running your program (=at "Design Time"),
Now we will learn how to do that during program's Run-Time.

To change a property, use the following syntax:

TheControlName.ThePropertyName = TheNewPropertyValue

For example, suppose we have Command Button


With the name "Command1", and we want to
set its Caption property to be "Hello".
To do that, we will use the following code:

Command1.Caption = "Hello"

To test it, simply copy the line above to your


Command1 Click event, run the program
and click the button at run-time.

Note that the Hello is inside quotes because


it's a String.
You can assign a variable value to a property:
Dim MyVar As String
MyVar = "Hello"
Command1.Caption = MyVar

This code will do exactly the same as the code line above it.
Note that MyVar is without quotes, because it's variable.

And how do you set a Form caption property at run-time?


exactly the same:

Form1.Caption = "Hello"

Setting Properties At Run-Time (Continue)


Not all the properties get text values.
For example, Visible property can be "True" or "False"

False and True are not text strings, but


Visual Basic commonly used values that called "Boolean"

Therefore, when you assign these values to property,


You don't have to use the quotes, For example:

Command1.Visible = False
Form1.Enabled = True

Some of the properties values has the following syntax:


Number - String

For example, the Command Button's Style property can


get 2 values:

0 - Standard
1 - Graphical

To set these properties value, omit the string.


For example:

Command1.Style = 1
Form1.WindowState = 2

Some properties represent graphics, for example


The Picture property.

To set these properties at run-time, use


the LoadPicture Command.
The example below will load the ICO file "d:\games\toto.ico"
to the Picture property of Command Button with the name "MyButton"

MyButton.Picture = LoadPicture("d:\games\toto.ico")
Setting the BackColor Property
You can set the BackColor property at run-time in 2 ways.

Way 1: Using the Color's numeric value


Every color has numeric value.
You can simply assign this value to the BackColor property.
For example, The numeric value of the red color is &H000000FF&
If you want to set the Form BackColor property to red,
use the following code:

Command1.BackColor = &H000000FF&

You can find what is the numeric value of every


color by making the following simple steps:

Click on the BackColor property arrow button


in the properties window (Figure 10).

Figure 10

Then click on the Palette Tab (Figure 11).

Figure 11

Select your desirable color (Figure 12).


Figure 12

The color value will be displayed in the BackColor Property cell (Figure 13).

Figure 13

And once again, if you setting a Command Button's color,


don't forget to set its Style property to 1 - Graphical.

To learn the second way, you'll have to learn


a little bit about Constants.

Way 2: Using the Colors Constants


First of all, what is Constant?
Constant is a variable that its value can not be changed.
Constant holds a common used value.
For example, the Constant vbRed holds the value
of the red color - &H000000FF&

Instead of writing in your code:

Command1.BackColor = &H000000FF&

You can write:

Command1.BackColor = vbRed

The 2 statements above are identical, because


vbRed = &H000000FF&
Where are these constants came from?
Visual Basic automatic declare them
when the program starts.

Imagine it like as the following code is


automatic being entered to your program:

Dim vbRed As Long


vbRed = &H000000FF&

Dim vbBlue As Long


vbBlue = &H00FF0000&

And so on...

But with one exception: You can't


change the constants value.

For example, the following code is NOT allowed:

vbBlue = 5

There are more Color constants, a partial list:

vbRed, vbBlue, vbBlack, vbGreen, vbWhite, vbYellow

You can declare your own constants.


The constant declaration syntax:

Const MyVariableName = MyVariableValue

For example, the following code will declare a const


variable with the name Piano and the (const) value "abcdef"

Const Piano = "abcdef"

After this declaration, the Print Piano


code line will print abcde on the form.

In addition, the following code line will not be allowed:

Piano = "gggg"

Because it's been declared as a Const,


and Const value can not be changed.

You might also like