Visual Basic
Visual Basic
Visual Basic
Visual basic evolved from BASIC(Beginners' All-purpose Symbolic Instruction Code). The BASIC
language was created by Professors John Kemeny and Thomas Kurtz of Dartmouth College in the mid
1960s(Deitel&Deitel, 1999) . It is a carefully constructed English-Like language basically used by the
programmers to write simple computer programs. It served the purpose of educating laymen like we all
the basic concepts of programming. From then on many versions of BASIC were developed to
accommodate different computer platforms. Some of the versions are Microsoft QBASIC, QUICKBASIC,
GWBASIC ,IBM BASICA, Apple BASIC and etc. Apple BASIC was developed by Steve Wozniak, a
former employee of Hewlett-Packard and a good friend of steve Jobs(the founded of Apple Inc.). Steve
Jobs had worked with Wozniak in the past (together they designed the arcade game "Breakout" for
Atari). They pooled their financial resources together to have PC boards made, and on April 1st, 1976
they officially formed the Apple Computer Company.
The popularity and widespread use of BASIC with different types of computers brought further
enhancements of the language, and eventually led to the GUI-based Visual Basic in tandem with the
development of Microsoft Windows. Visual Basic made programming even easier for beginners and
season programmers alike as it save considerable programming time by providing many ready-made
components. Since then, Visual Basic has also evolved into many versions, until recently, Visual Basic
2008. However, Visual Basic 6 remains as one of the most popular version as it is easy to program and it
doesn't take up a lot of resources and memory of the computerThe concept of computer programming
Before we begin programming, let us understand some basic concepts of programming. According to
Webopedia, a computer program is an organized list of instructions that, when executed, causes the
computer to behave in a predetermined manner. Without programs, computers are useless. Therefore,
programming means designing or creating a set of instructions to ask the computer to carry out certain
jobs which normally are very much faster than human beings can do.
A lot of people think that computer CPU is a very intelligent thing, which in actual fact it is a dumb and
inanimate object that can do nothing without human assistant. The microchips of a CPU can only
understand two distinct electrical states, namely, the on and off states, or 0 and 1 codes in the binary
system. So, the CPU only understands a combinations of 0 and 1 codes, a language which we called
machine language. Machine language is extremely difficult to learn and it is not for us laymen to master it
easily. Fortunately , we have many smart programmers who wrote interpreters and compilers that can
translate human language-like programs such as BASIC into machine language so that the computer can
carry out the instructions entered by the users. Machine language is known as the primitive language
while Interpreters and compilers like Visual Basic are called high-level language. Some of the high level
computer languages beside Visual Basic are Fortran, Cobol, Java, C, C++, Turbo Pascal, and etc .
FORTRAN stands for FORmula TRANslator and it was developed by IBM Inc. between 1954 and 1957
which was used specifically for scientific ad engineering applications. It is still widely used today in the
engineering fields. COBOL stands for Common Business Oriented Language which was created by a
group of computer manufacturers and industrial computer users in 1959. It was designed for commercial
applications that required large amount of data processing. It is still being used today in the business
fields. C was developed by Dennis Richie at Bell Laboratories in 1972. It is a system implementation
language that was used to develop the UNIX operating system. C++ is an extension of C which was
created by Bjarne Stroustrup in 1980's. It added the OOP (Object-Oriented Programming) feature to C
and now it is the main systems implementation language (Deitel&Deitel, 1999) . PASCAL was created by
Professor Nicklaus Wirth for teaching the concepts of structured programming. Its use is primarily
confined to the academic world. JAVA is the latest but one of the hottest programming languages
developed by the Sun Microsystems in 1995. It was actually an extension of C++ but it has included
extensive libraries for doing multimedia, networking, multithreading , graphics, database access, GUI
programming. Microsoft also come out with its own version of Javawhich is known as Visual J++. Other
programming languages are Power Builder which was developed by Powersoft Corporation and Delphi
which was developed by Borland Inc.
Before we begin, let us understand some basic concepts of programming. According to Webopedia, a
computer program is an organized list of instructions that, when executed, causes the computer to
behave in a predetermined manner. Without programs, computers are useless. Therefore, programming
means designing or creating a set of instructions to ask the computer to carry out certain jobs which
normally are very much faster than human beings can do. In order to do programming, we need to use
certain computer language to communicate with the computer.There are many computer languages out
there, some of the examples are Visual Basic, Fortran, Cobol, Java, C++, Turbo Pascal, Assembly
language and etc.
With Visual Basic, you can program practically everything depending on your objective. For example, you
can program educational software to teach science , mathematics, language, history , geography and so
on. You can also program financial and accounting software to make you a more efficient accountant or
financial controller. For those of you who like games, you can program that as well. Indeed, there is no
limit to what you can program! There are many such program in this tutorial, so you must spend more
time on the tutorial in order to benefit the most.
VISUAL BASIC is a VISUAL and events driven Programming Language. These are the main divergence
from the old BASIC. In BASIC, programming is done in a text-only environment and the program is
executed sequentially. In VISUAL BASIC, programming is done in a graphical environment. In the old
BASIC, you have to write program codes for each graphical object you wish to display it on screen,
including its position and its color. However, In Visual Basic , you just need to drag and drop any
graphical object anywhere on the form, and you can change its color any time using the properties
windows.
On the other hand, because users may click on a certain object randomly, so each object has to be
programmed independently to be able to response to those actions (events). Therefore, a VISUAL BASIC
Program is made up of many subprograms, each has its own program codes, and each can be executed
independently and at the same time each can be linked together in one way or another.
Before you can program in Visual Basic, you need to install VB6 in your computer. If you do not own VB6
yet , you can purchase it from Amazon.com by clicking the link below:
Microsoft Visual Basic 6.0 Professional
Basically any present computer systems should be able to run the program, be it a Intel Pentium II, Intel
Pentium III, Intel Pentium IV or even AMD machines, VB6 can run without any problem. It may not be true
for VB2005, older machines might not be able to run VB2005 as it take up much more resources,
therefore I still prefer using VB6 as it is light and easy to program. It is still very useful and powerful, and I
am happy to know that Microsoft Windows Vista can support VB6.
On start up, Visual Basic 6.0 will display the following dialog box as shown in figure 1.1. You can choose
to either start a new project, open an existing project or select a list of recently opened programs. A
project is a collection of files that make up your application. There are various types of applications we
could create, however, we shall concentrate on creating Standard EXE programs (EXE means executable
program). Now, click on the Standard EXE icon to go into the actual VB programming environment.
In this section, we are not going into the technical aspects of VB programming; just have a feel of it.
Now, you can try out the examples below:
Example 2.1.1 is a simple program. First of all, you have to launch Microsoft Visual Basic. Normally, a
default form Form1 will be available for you to start your new project. Now, double click on form1, the
source code window for form1 as shown in figure 2.1 will appear. The top of the source code window
consists of a list of objects and their associated events or procedures. In figure 2.1, the object displayed is
Form and the associated procedure is Load.
When you click on the object box, the drop-down list will display a list of objects you have inserted into
your form as shown in figure 2.2. Here, you can see a form, command button with the name Command1,
a Label with the name Label1 and a PictureBox with the name Picture1. Similarly, when you click on the
procedure box, a list of procedures associated with the object will be displayed as shown in figure 2.3.
Some of the procedures associated with the object Form are Activate, Click, DblClick (which means
Double-Click) , DragDrop, keyPress and etc. Each object has its own set of procedures. You can always
select an object and write codes for any of its procedure in order to perform certain tasks.
You do not have to worry about the beginning and the end statements (i.e. Private Sub
Form_Load.......End Sub.); Just key in the lines in between the above two statements exactly as are
shown here. When you run the program, you will be surprise that nothing shown up .In order to display
the output of the program, you have to add the Form1.show statement like in Example 2.1.1 or you can
just use Form_Activate ( ) event procedure as shown in example 2.1.2. The command Print does not
mean printing using a printer but it means displaying the output on the computer screen. Now, press F5 or
click on the run button to run the program and you will get the output as shown in figure 2.4.
You can also perform simple arithmetic calculations as shown in example 2.1.2. VB uses * to denote the
multiplication operator and / to denote the division operator. The output is shown in figure 2.3, where the
results are arranged vertically
Generally, there are three basic steps in building a VB application. The steps are as follows:
Figure 3.1 on the right is a typical properties window for a form. You can rename the form caption to any
name that you like best. In the properties window, the item appears at the top part is the object currently
selected (in Figure 3.1, the object selected is Form1). At the bottom part, the items listed in the left
column represent the names of various properties associated with the selected object while the items
listed in the right column represent the states of the properties. Properties can be set by highlighting the
items in the right column then change them by typing or selecting the options available.
For example, in order to change the caption, just highlight Form1 under the name Caption and change it
to other names. You may also try to alter the appearance of the form by setting it to 3D or flat. Other
things you can do are to change its foreground and background color, change the font type and font size,
enable or disable minimize and maximize buttons and etc.
You can also change the properties at runtime to give special effects such as change of color, shape,
animation effect and so on. For example the following code will change the form color to red every time
the form is loaded. VB uses hexadecimal system to represent the color. You can check the color codes in
the properties windows which are showed up under ForeColor and BackColor .
Another example is to change the control Shape to a particular shape at runtime by writing the following
code. This code will change the shape to a circle at runtime. Later you will learn how to change the
shapes randomly by using the RND function.
I am not going into the details on how to set the properties. However, I would like to stress a few
important points about setting up the properties.
• You should set the Caption Property of a control clearly so that a user knows what to do with that
command. For example, in the calculator program, all the captions of the command buttons such
as +, - , MC, MR are commonly found in an ordinary calculator, a user should have no problem in
manipulating the buttons.
• A lot of programmers like to use a meaningful name for the Name Property may be because it is
easier for them to write and read the event procedure and easier to debug or modify the
programs later. However, it is not a must to do that as long as you label your objects clearly and
use comments in the program whenever you feel necessary. T
The text box is the standard control that is used to receive input from the user as well as to display the
output. It can handle string (text) and numeric data but not images or pictures. String in a text box can be
converted to a numeric data by using the function Val(text). The following example illustrates a simple
program that processes the inputs from the user.
Example 3.1
In this program, two text boxes are inserted into the form together with a few labels. The two text boxes
are used to accept inputs from the user and one of the labels will be used to display the sum of two
numbers that are entered into the two text boxes. Besides, a command button is also programmed to
calculate the sum of the two numbers using the plus operator. The program use creates a variable sum to
accept the summation of values from text box 1 and text box 2.The procedure to calculate and to display
the output on the label is shown below. The output is shown in Figure 3.2
Label1.Caption = Sum
End Sub
Figure 3.2
3.2.2 The Label
The label is a very useful control for Visual Basic, as it is not only used to provide instructions and guides
to the users, it can also be used to display outputs. One of its most important properties is Caption. Using
the syntax label.Caption, it can display text and numeric data . You can change its caption in the
properties window and also at runtime. Please refer to Example 3.1 and Figure 3.1 for the usage of label.
The command button is a very important control as it is used to execute commands. It displays an illusion
that the button is pressed when the user click on it. The most common event associated with the
command button is the Click event, and the syntax for the procedure is
Statements
End Sub
The Picture Box is one of the controls that used to handle graphics. You can load a picture at design
phase by clicking on the picture item in the properties window and select the picture from the selected
folder. You can also load the picture at runtime using the LoadPicture method. For example, the
statement will load the picture grape.gif into the picture box.
You will learn more about the picture box in future lessons. The image in the picture box is not resizable.
The Image Box is another control that handles images and pictures. It functions almost identically to the
picture box. However, there is one major difference, the image in an Image Box is stretchable, which
means it can be resized. This feature is not available in the Picture Box. Similar to the Picture Box, it can
also use the LoadPicture method to load the picture. For example, the statement loads the picture
grape.gif into the image box.
Image1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")
The function of the List Box is to present a list of items where the user can click and select the items from
the list. In order to add items to the list, we can use the AddItem method. For example, if you wish to add
a number of items to list box 1, you can key in the following statements
Example 3.2
List1.AddItem “Lesson1”
List1.AddItem “Lesson2”
List1.AddItem “Lesson3”
List1.AddItem “Lesson4”
End Sub
The items in the list box can be identified by the ListIndex property, the value of the ListIndex for the first
item is 0, the second item has a ListIndex 1, and the second item has a ListIndex 2 and so on
The function of the Combo Box is also to present a list of items where the user can click and select the
items from the list. However, the user needs to click on the small arrowhead on the right of the combo box
to see the items which are presented in a drop-down list. In order to add items to the list, you can also use
the AddItem method. For example, if you wish to add a number of items to Combo box 1, you can key in
the following statements
Example 3.3
Combo1.AddItem “Item1”
Combo1.AddItem “Item2”
Combo1.AddItem “Item3”
Combo1.AddItem “Item4”
End Sub
3.2.8 The Check Box
The Check Box control lets the user to select or unselect an option. When the Check Box is checked, its
value is set to 1 and when it is unchecked, the value is set to 0. You can include the statements
Check1.Value=1 to mark the Check Box and Check1.Value=0 unmark the Check Box, and use them to
initiate certain actions. For example, the program will change the background color of the form to red
when the check box is unchecked and it will change to blue when the check box is checked. You will
learn about the conditional statement If….Then….Elesif in later lesson. VbRed and vbBlue are color
constants and BackColor is the background color property of the form.
The Option Box control also lets the user selects one of the choices. However, two or more Option Boxes
must work together because as one of the Option Boxes is selected, the other Option Boxes will be
unselected. In fact, only one Option Box can be selected at one time. When an option box is selected, its
value is set to “True” and when it is unselected; its value is set to “False”. In the following example, the
shape control is placed in the form together with six Option Boxes. When the user clicks on different
option boxes, different shapes will appear. The values of the shape control are 0, 1, and 2,3,4,5 which will
make it appear as a rectangle, a square, an oval shape, a rounded rectangle and a rounded square
respectively.
Example 3.4
Private Sub Option1_Click ( )
Shape1.Shape = 0
End Sub
Private Sub Option2_Click()
Shape1.Shape = 1
End Sub
Private Sub Option3_Click()
Shape1.Shape = 2
End Sub
Private Sub Option4_Click()
Shape1.Shape = 3
End Sub
Private Sub Option5_Click()
Shape1.Shape = 4
End Sub
Private Sub Option6_Click()
Shape1.Shape = 5
End Sub
The Drive ListBox is used to display a list of drives available in your computer. When you place this
control into the form and run the program, you will be able to select different drives from your computer as
shown in Figure 3.3
The Directory List Box is used to display the list of directories or folders in a selected drive. When you
place this control into the form and run the program, you will be able to select different directories from a
selected drive in your computer as shown in Figure 3.4
FigureBox
The File List Box is used to display the list of files in a selected directory or folder. When you place this
control into the form and run the program, you will be able to a list of files in a selected directory as shown
in Figure 3.5
You can coordinate the Drive List Box, the Directory List Box and the File List Box to search for the files
you want. The procedure will be discussed in later.
Each control or object in VB can usually run many kinds of events or procedures; these events are
listed in the dropdown list in the code window that is displayed when you double-click on an object and
click on the procedures’ box(refer to Figure 2.3). Among the events are loading a form, clicking of a
command button, pressing a key on the keyboard or dragging an object and etc. For each event, you
need to write an event procedure so that an action or a series of actions can be performed.
To start writing an event procedure, you need to double-click an object. For example, if you want to write
an event procedure when a user clicks a command button, you double-click on the command button
and an event procedure will appear as shown in Figure 2.1. It takes the following format:
End Sub
You then need to key-in the procedure in the space between Private Sub Command1_Click............. End
Sub. Sub actually stands for sub procedure that made up a part of all the procedures in a program. The
program code is made up of a number of statements that set certain properties or trigger some actions.
The syntax of Visual Basic’s program code is almost like the normal English language though not exactly
the same, so it is very easy to learn.
Object.Property
where Object and Property is separated by a period (or dot). For example, the statement Form1.Show
means to show the form with the name Form1, Iabel1.Visible=true means label1 is set to be visible,
Text1.text=”VB” is to assign the text VB to the text box with the name Text1, Text2.text=100 is to pass a
value of 100 to the text box with the name text2, Timer1.Enabled=False is to disable the timer with the
name Timer1 and so on. Let’s examine a few examples below:
You then need to key-in the procedure in the space between Private Sub Command1_Click............. End
Sub. Sub actually stands for sub procedure that made up a part of all the procedures in a program. The
program code is made up of a number of statements that set certain properties or trigger some actions.
The syntax of Visual Basic’s program code is almost like the normal English language though not exactly
the same, so it is very easy to learn.
Example 4.1
Example 4.2
Private Sub Command1_click
Private Sub Command1_click
Label1.Visible=false
Label1.Caption=”
Label2.Visible=True Welcome”
Example 4.3
Pictuire1.Show=true
Timer1.Enabled=True
Lable1.Caption=”Start
Counting
End sub
In example 4.1, clicking on the command button will make label1 become invisible and label2 become
visible; and the text” You are correct” will appear in TextBox1. In example 4.2, clicking on the command
button will make the caption label1 change to “Welcome” and Image1 will become visible. In example
4.3 , clicking on the command button will make Picture1 show up, timer starts running and the caption of
label1 change to “Start Counting”.
Syntaxes that do not involve setting of properties are also English-like, some of the commands are Print,
If…Then….Else….End If, For…Next, Select Case…..End Select , End and Exit Sub. For example,
Print “ Visual Basic” is to display the text Visual Basic on screen and End is to end the program. Other
commands will be explained in details in the coming lessons.
Program codes that involve calculations is very easy to write, you need to write them almost liket what
you do in mathematics. However, in order to write an event procedure that involves calculations, you
need to know the basic arithmetic operators in VB as they are not exactly the same as the normal
operators we use, except for + and - . For multiplication, we use *, for division we use /, for raising a
number x to the power of n, we use x ^n and for square root, we use Sqr(x). More advanced
mathematical functions such as Sin, Cos, Tan , Log and etc. There are also two important functions that
are related to arithmetic operations, i.e. the functions Val and Str$ where Val is to convert text entered
into a textbox to numerical value and Str$ is to display a numerical value in a textbox as a string (text).
While the function Str$ is as important as VB can display a numeric values as string implicitly, failure to
use Val will results in wrong calculation. Let’s examine example 4.4 and example 4.5.
Example 4.5
Example 4.4
Text3.text=text1.text+text2.text Text3.text=val(text1.text)+val(text2.text)
When you run the program in example 4.4 and enter 12 in textbox1 and 3 in textbox2 will give you a result
of 123, which is wrong. It is because VB treat the numbers as string and so it just joins up the two strings.
On the other hand, running exampled 4.5 will give you the correct result, i.e., 15
Lesson 5: Managing Visual Basic Data
There are many types of data that we come across in our daily life. For example, we need to handle data
such as names, addresses, money, date, stock quotes, statistics and etc everyday. Similarly in Visual
Basic, we have to deal with all sorts of of data, some can be mathematically calculated while some are in
the form of text or other forms. VB divides data into different types so that it is easier to manage when we
need to write the code involving those data
Visual Basic classifies the information mentioned above into two major data types, they are the numeric
data types and the non-numeric data types.
Numeric data types are types of data that consist of numbers, which can be computed mathematically
with various standard operators such as add, minus, multiply, divide and so on. Examples of numeric
data types are your examination marks, your height, your weight, the number of students in a class,
share values, price of goods, monthly bills, fees and etc. In Visual Basic, numeric data are divided into 7
types, depending on the range of values they can store. Calculations that only involve round figures or
data that don't need precision can use Integer or Long integer in the computation. Programs that require
high precision calculation need to use Single and Double decision data types, they are also called
floating point numbers. For currency calculation , you can use the currency data types. Lastly, if even
more precision is requires to perform calculations that involve a many decimal points, we can use the
decimal data types. These data types summarized in Table 5.1
Type Storage
Range of Values
Byte 1 byte0 to 255
Integer 2 bytes
-32,768 to 32,767
Long 4 bytes
-2,147,483,648 to 2,147,483,648
-3.402823E+38 to -1.401298E-45 for negative values
Single 4 bytes
1.401298E-45 to 3.402823E+38 for positive values.
-1.79769313486232e+308 to -4.94065645841247E-324 for
negative values
Double 8 bytes
4.94065645841247E-324 to 1.79769313486232e+308 for
positive values.
Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807
Decimal 12 bytes +/- 79,228,162,514,264,337,593,543,950,335 if no decimal
is use
+/- 7.9228162514264337593543950335 (28 decimal
places).
Nonnumeric data types are data that cannot be manipulated mathematically using standard arithmetic
operators. The non-numeric data comprises text or string data types, the Date data types, the Boolean
data types that store only two values (true or false), Object data type and Variant data type .They are
summarized in Table 5.2
Literals are values that you assign to a data. In some cases, we need to add a suffix behind a literal so that
VB can handle the calculation more accurately. For example, we can use num=1.3089# for a Double type
data. Some of the suffixes are displayed in Table 5.3.
Table 5.3
In addition, we need to enclose string literals within two quotations and date and time literals within two #
sign. Strings can contain any characters, including numbers. The following are few examples:
memberName="Turban, John."
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#
5.2 Managing Variables
Variables are like mail boxes in the post office. The contents of the variables changes every now and
then, just like the mail boxes. In term of VB, variables are areas allocated by the computer memory to
hold data. Like the mail boxes, each variable must be given a name. To name a variable in Visual Basic,
you have to follow a set of rules.
The following are the rules when naming the variables in Visual Basic
Examples of valid and invalid variable names are displayed in Table 5.4
Table 5.4
In Visual Basic, one needs to declare the variables before using them by assigning names and data
types. They are normally declared in the general section of the codes' windows using the Dim statement.
The format is as follows:
Example 5.1
You may also combine them in one line , separating each variable with a comma, as follows:
If data type is not specified, VB will automatically declare the variable as a Variant.
For string declaration, there are two possible formats, one for the variable-length string and another for
the fixed-length string. For the variable-length string, just use the same format as example 5.1 above.
However, for the fixed-length string, you have to use the format as shown below:
Dim VariableName as String * n, where n defines the number of characters the string can hold.
Example 5.2:
5.3 Constants
Constants are different from variables in the sense that their values do not change during the running of
the program.
Example 5.3
Const Pi As Single=3.142
After declaring various variables using the Dim statements, we can assign values to those variables. The
general format of an assignment is
Variable=Expression
The variable can be a declared variable or a control property value. The expression could be a
mathematical expression, a number, a string, a Boolean value (true or false) and etc. The following are
some examples:
firstNumber=100
secondNumber=firstNumber-99
userName="John Lyan"
userpass.Text = password
Label1.Visible = True
Command1.Visible = false
Label4.Caption = textbox1.Text
ThirdNumber = Val(usernum1.Text)
total = firstNumber + secondNumber+ThirdNumber
In order to compute inputs from users and to generate results, we need to use various mathematical
operators. In Visual Basic, except for + and -, the symbols for the operators are different from normal
mathematical operators, as shown in Table 6.1.
Exponential 2^4=16
^
Multiplication 4*3=12, (5*6))2=60
*
Division 12/4=3
/
Modulus(return the
15 Mod 4=3 255 mod
remainder from an integer
Mod 10=5
division)
Integer Division(discards
19\4=4
\ the decimal places)
"Visual"&"Basic"="Visual
+ or & String concatenation Basic"
To control the VB program flow, we can use various conditional operators. Basically, they resemble
mathematical operators. Conditional operators are very powerful tools, they let the VB program compare
data values and then decide what action to take, whether to execute a program or terminate the program
and etc. These operators are shown in Table 7.1.
In addition to conditional operators, there are a few logical operators which offer added power to the VB
programs. There are shown in Table 7.2.
* You can also compare strings with the above operators. However, there are certain rules to follows:
Upper case letters are less than lowercase letters, "A"<"B"<"C"<"D".......<"Z" and number are less than
letters.
To effectively control the VB program flow, we shall use Private Sub OK_Click()
If...Then...Else statement together with the conditional operators and
logical operators. firstnum = Val(usernum1.Text)
The general format for the if...then...else statement is
secondnum = Val(usernum2.Text)
If conditions Then total = Val(sum.Text)
VB expressions If total = firstnum + secondnum And
Val(sum.Text) <> 0 Then
Else correct.Visible = True
VB expressions wrong.Visible = False
Else
End If correct.Visible = False
wrong.Visible = True
* any If..Then..Else statement must end with End If. Sometime it is End If
not necessary to use Else.
End Sub
Block
of one or
more VB
Statements
End Select
* The data
type
specified in
expression
must match
that of Case
values.
End Sub
Lesson 9: Looping
Sometime we need
exit to exit a loop
prematurely because
of a certain condition Example 9.3 a Example 9.3 b
is fulfilled. The syntax For counter=1 to 10 For counter=1 to 1000 step 10
to use is known as display.Text=counter counter=counter+1
Exit Do. Lets examine Next Next
the folowing example
A function is similar to a normal procedure but the main purpose of the functios is to accept a certain
input and return a value which is passed on to the main program to finish the execution. There are two
types of functions, the built-in functions (or internal functions) and the functions created by the
programmers
In this lesson, we are going to learn two very basic but useful internal functions of Visual basic , i.e. the
MsgBox( ) and InputBox ( ) functions. You can also learn about mathematical functions, formatting
functions and string manipulation functions by clicking the links at the end of this page.
The objective of MsgBox is to produce a pop-up message box and prompt the user to click on a command
button before he /she can continues. This format is as follows:
The first argument, Prompt, will display the message in the message box. The Style Value will determine
what type of command buttons appear on the message box, please refer Table 10.1 for types of command
button displayed. The Title argument will display the title of the message board.
0 vbOkOnly Ok button
We can use named constant in place of integers for the second argument to make the programs more
readable. In fact, VB6 will automatically shows up a list of names constant where you can select one of
them.
yourMsg is a variable that holds values that are returned by the MsgBox ( ) function. The values are
determined by the type of buttons being clicked by the users. It has to be declared as Integer data type in
the procedure or in the general declaration section. Table 10.2 shows the values, the corresponding named
constant and buttons.
Button
Value Named Constant
Clicked
Ok
1 vbOk
button
Cancel
2 vbCancel
button
Abort
3 vbAbort
button
Retry
4 vbRetry
button
Ignore
5 vbIgnore
button
Yes
6 vbYes
button
No
7 vbNo
button
End Sub
End Sub
48 vbExclamation
In this example, the following message box will be
displayed:
An InputBox( ) function will display a message ii. The procedure for the OK button
box where the user can enter a value or a
message in the form of text. The format is Private Sub OK_Click()
Dim userMsg As String
myMessage=InputBox(Prompt, Title, default_text, userMsg = InputBox("What is your message?",
x-position, y-position) "Message Entry Form", "Enter your messge here", 500,
700)
If userMsg <> "" Then
myMessage is a variant data type but typically it
message.Caption = userMsg
is declared as string, which accept the message
Else
input by the users. The arguments are explained
message.Caption = "No Message"
as follows:
End If
End Sub
• Prompt - The message displayed
normally as a question asked.
When a user click the OK button, the input box as shown
• Title - The title of the Input Box.
in Figure 10.5 will appear. After user entering the
• default-text - The default text that message and click OK, the message will be displayed on
appears in the input field where users the caption, if he click Cancel, "No message" will be
can use it as his intended input or he may displayed.
change to the message he wish to key in.
• x-position and y-position - the position or
the coordinate of the input box.
Example 10.3
i. The Interface
Figure 10.4
Lesson 11: Introduction to VB Functions- Part II
or
* Public indicates that the function is applicable to the whole program and
Private indicates that the function is only applicable to a certain module or procedure.
Example 11.1
In this example, a user can calculate future value of a certain amount of money he has today based
on the interest rate and the number of years from now supposing he will invest this amount of money
somewhere .The calculation is based on the compound interest rate.
Table 12.1:
Commission
s Payment
Table
Sales
Volu Comm
me($ issons
)
<500 3%
<100
6%
0
<200
9%
0
<500
12%
0
>500
15%
0
12.2 Using Microsoft Excel Visual Basic Upon clicking the Visual Basic Editor, the
Editor VB Editor windows will appear as shown in
figure 12.2. To create a function, type in
To create User Defined functions in MS Excel, the function as illustrated in section 12.1
you can click on tools, above After typing, save the file and then
select macro and then click on Visual Basic return to the Excel windows.
Editor as shown in Figure 12.1
Figure 12.2 : The VB Editor
Stu
13.2 Declaring Arrays
Example 13.1
CusN CusN CusN CusN CusN CusN CusN CusN CusN CusNa
ame( ame( ame( ame( ame( ame( ame( ame( ame( me(10
1) 2) 3) 4) 5) 6) 7) 8) 9) )
Example 13.2
Example 13.3
The above
program accepts
data entries
through an
InputBox and
displays the items
in a list box.
Up until lesson 13 we are only creating programs that could accept data at runtime, when the program is
terminated, the data also disappear. Is it possible to save data accepted by a VB program into a storage
device, such as a hard disk or diskette, or even CDRW? The answer is possible. In this chapter, we will
learn how to create files by writing them into a storage device and then retrieve the data by reading the
contents of the files using a customized VB program.
Close #1
* The above program will create a file sample.txt in the My Documents' folder and ready to receive input
from users. Any data input by users will be saved in this text file.
14.3 Reading files
To read a file created in section 14.2, you can use the input # statement. However, we can only read the
file according to the format when it was written. You have to open the file according to its file number and
the variable that hold the data. We also need to declare the variable using the DIM command.
End Sub
* This program will open the sample.txt file and display its contents in the Text1 textbox.
Example 14.3.2 Creating The syntax CommonDialog1.Filter = "Text files{*.txt)|*.txt" ensures that only
and Reading files using the textfile is read or saved .The statement CommonDialog1.ShowOpen is to
Common Dialog Box display the
open file dialog box and the statement CommonDialog1.ShowSave is to
This example uses the display the
common dialog box to save file dialog box. Text1.Text = Text1.Text & linetext is to read the data and
create and read the text file, display
which is them in the Text1 textbox
much easier than the
previous examples as many The Output window is shown below:
operations are handled by
the
common dialog box. The
following is the program:
To be able to play multimedia files or multimedia devices, you have to insert Microsoft
Multimedia Control into your VB applications
that you are going to create. However, Microsoft Multimedia Control is not normally included in
the startup toolbox, therefore you need
to add the MM control by pressing Ctrl+T and select it from the components dialog box that is
displayed.
First of all, you place a Multimedia control into your form and rename it as any name of your
choice. Here I use myCD to replace the default name MMControl1. Next, you can put two labels
on your form, change caption of the left label to Track and rename the one on the right to
trackNum and make its caption invisible(this lable is to display CD track numbers at runtime.).
Finally, put five command buttons in your form and name them as Play, Next, Previous, Stop
and Exit. You can also choose to make the MM Control visible or invisible at runtime. If you
choose to make it visible,you could play the CD using the buttons available on the control itself
or you can click on the buttons at the bottom that are created by you.
End Sub
Private Sub myCD_StatusUpdate()
‘Update the track number
trackNum.Caption = myCD.Track
End Sub
Private Sub Next_Click()
myCD.Command = “Next”
End Sub
End Sub
In previous lesson, we have programmed a CD player. Now, with some modifications, we will transform
the CD player into an audio file player. This player will be created in such a way that it could search for
wave and midi files in your drives and play them.
In this project, you need to insert a ComboBox, a DriveListBox, a DirListBox, a TextBox and a FileListBox
into your form.I Shall briefly discuss the function of each of the above controls. Besides, you must also
insert Microsoft Multimedia Control(MMControl) in your form , you may make it visible or invisible. In my
program, I choose to make it invisible so that I can use the command buttons created to control the
player.
Relevant code must be written to coordinate all the above controls so that the application can work
properly. The program should follow in the following logical way:
Step2:User selects the drive that might contains the relevant audio files.
Step 3:User looks into directories and subdirectories for the files specified in step1. The files should be
displayed in the FileListBox.
Step 4: User selects the files from the FileListBox and click the Play button.
Step 5: User click on the Stop to stop playing and Exit button to end the application.
The Interface
The Code
Private Sub Combo1_Change()
' to determine file type
If ListIndex = 0 Then
File1.Pattern = ("*.wav")
ElseIf ListIndex = 1 Then
File1.Pattern = ("*.mid")
Else
Fiel1.Pattern = ("*.*")
End If
End Sub
End Sub
Similar to the previous project, in this project, you need to insert a ComboBox, a DriveListBox, a
DirListBox, a TextBox and a FileListBox into your form. I Shall briefly explain again the function of each of
the above controls.
Relevant codes must be written to coordinate all the above controls so that the application can work
properly. The program should flow in the following logical way:
Step 1: User choose the type of files he wants to play.
Step2:User selects the drive that might contains the relevant graphic files.
Step 3:User looks into directories and subdirectories for the files specified in step1. The files should be
displayed in the FileListBox.
Step 4: User selects the files from the FileListBox and click the Show button.
The Interface
Private Sub File1_Click()
If Combo1.ListIndex = 0
The Code
Then
File1.Pattern =
Private Sub Form_Load() ("*.bmp;*.wmf;*.jpg;*.gif")
Left = (Screen.Width - Width) \ 2 Else
Top = (Screen.Height - Height) \ 2 File1.Pattern = ("*.*")
End If
In lesson 16, we have created an audio player. Now, with some modifications, we will transform the audio
player into a multimedia player that could play all kinds of movie files besides audio files. This player will
be created in such a way that it could search for all types of graphics your drives and play them.
In this project, you need to insert a ComboBox, a DriveListBox, a DirListBox, a TextBox ,a FileListBox
and a picture box (for playing movie) into your form. I Shall briefly discuss the function of each of the
above controls. Besides, you must also insert Microsoft Multimedia Control(MMControl) in your form , you
may make it visible or invisible. In my program, I choose to make it invisible so that I could use the
command buttons created to control the player.
Relevant codes must be written to coordinate all the above controls so that the application can work
properly. The program should flow in the following logical way:
Step2:User selects the drive that might contains the relevant audio files.
Step 3:User looks into directories and subdirectories for the files specified in step1. The files should be
displayed in the FileListBox.
Step 4: User selects the files from the FileListBox and click the Play button.
Step 5: User click on the Stop to stop playing and Exit button to end the application.
The Interface
The Codes Private Sub Drive1_Change()
Private Sub Form_Load()
Left = (Screen.Width - Dir1.Path = Drive1.Drive
Width) \ 2 End Sub
Top = (Screen.Height -
Height) \ 2
Combo1.Text = "*.wav" Private Sub File1_Click()
Combo1.AddItem "*.wav" If Combo1.ListIndex = 0 Then
Combo1.AddItem "*.mid" File1.Pattern = ("*.wav")
Combo1.AddItem ElseIf Combo1.ListIndex = 1 Then
"*.avi;*.mpg" File1.Pattern = ("*.mid")
Combo1.AddItem "All files" ElseIf Combo1.ListIndex = 2 Then
End Sub File1.Pattern = ("*.avi;*.mpg")
Else
Private Sub File1.Pattern = ("*.*")
Combo1_Change() End If
If ListIndex = 0 Then
File1.Pattern = ("*.wav") If Right(File1.Path, 1) <> "\" Then
ElseIf ListIndex = 1 Then filenam = File1.Path + "\" + File1.FileName
File1.Pattern = ("*.mid") Else
ElseIf ListIndex = 2 Then filenam = File1.Path + File1.FileName
File1.Pattern = End If
("*.avi;*.mpg") Text1.Text = filenam
Else
Fiel1.Pattern = ("*.*") End Sub
End If
End Sub Private Sub play_Click()
MMPlayer.FileName = Text1.Text
Private Sub Dir1_Change() MMPlayer.Command = "Open"
File1.Path = Dir1.Path MMPlayer.Command = "Play"
If Combo1.ListIndex = 0 MMPlayer.hWndDisplay = videoscreen.hWnd
Then End Sub
File1.Pattern = ("*.wav")
ElseIf Combo1.ListIndex =
1 Then Private Sub stop_Click()
File1.Pattern = ("*.mid") If MMPlayer.Mode = 524 Then Exit Sub
ElseIf Combo1.ListIndex = If MMPlayer.Mode <> 525 Then
2 Then MMPlayer.Wait = True
File1.Pattern = MMPlayer.Command = "Stop"
("*.avi;*.mpg") End If
Else MMPlayer.Wait = True
File1.Pattern = ("*.*") MMPlayer.Command = "Close"
End If End Sub
End Sub
Lesson 19: Creating database applications in
VB-Part I
Visual basic allows us to manage databases created with different database programs such as MS
Access, Dbase, Paradox and etc. In this lesson, we are not dealing with how to create database files but
In the following example, we will create a simple database application which enable one to browse
customers' names. To create this application, insert the data control into the new form. Place the data
control somewhere at the bottom of the form. Name the data control as data_navigator. To be able to use
the data control, we need to connect it to any database. We can create a database file using any
database application but I suggest we use the database files that come with VB6. Let select NWIND.MDB
as our database file. To connect the data control to this database, double-click the DatabaseName
property in the properties window and select the above file, i.e NWIND.MDB. Next, double-click on the
RecordSource property to select the customers table from the database. You can also change the caption
of the data control to anything but I use "Click to browse Customers" here. After that, we will place a label
and change its caption to Customer Name. Last but not least, insert another label and name it as
cus_name and leave the label empty as customers' names will appear here when we click the arrows on
the data control. We need to bind this label to the data control for the application to work. To do this, open
the label's DataSource and select data_navigator that will appear automatically. One more thing that we
need to do is to bind the label to the correct field so that data in this field will appear on this label. To do
this, open the DataField property and select ContactName. Now, press F5 and run the program. You
should be able to browse all the customers' names by clicking the arrows on the data control.
The Design Interface.
You can also add, save and delete records using the following commands:
In the following example, you shall insert four commands and label them as First Record, Next Record,
Previous Record and Last Record . They will be used to navigator around the database without using the
data control. You still need to retain the same data control (from example in lesson 19) but set the
property Visible to no so that users will not see the data control but use the button to browse through the
database instead. Now, double-click on the command button and key in the codes according to the
labels.
To be able to use ADO data control, you need to insert it into the toolbox. To do this, simply press Ctrl+T
to open the components dialog box and select Microsoft ActiveX Data Control 6. After this, you can
proceed to build your ADO-based VB database applications.
The following example will illustrate how to build a relatively powerful database application using ADO
data control. First of all, name the new form as frmBookTitle and change its caption to Book Titles- ADO
Application. Secondly, insert the ADO data control and name it as adoBooks and change its caption to
book. Next, insert the necessary labels, text boxes and command buttons. The runtime interface of this
program is shown in the diagram below, it allows adding and deletion as well as updating and browsing of
data.
The properties of all the controls are listed as follow:
To be able to access and manage a database, you need to connect the ADO data control to a database
file. We are going to use BIBLIO.MDB that comes with VB6. To connect ADO to this database file , follow
the steps below:
a) Click on the ADO control on the form and open up the properties window.
b) Click on the ConnectionString property, the following dialog box will appear.
when the dialog box appear, select the Use Connection String's Option. Next, click build and at the Data
Link dialog box, double-Click the option labeled Microsoft Jet 3.51 OLE DB provider.
After that, click the Next button to select the file BIBLO.MDB. You can click on Text Connection to ensure
proper connection of the database file. Click OK to finish the connection.
Finally, click on the RecordSource property and set the command type to adCmd Table and Table name
to Titles. Now you are ready to use the database file.
Now, you need to write code for all the command buttons. After which, you can make the ADO control
invisible.
End Sub
End Sub
End Sub
For the Next(>) button, the program codes are
End Sub
Lesson 22: Creating an Advanced VB database application using ADO
control
In previous lessons, you have learned how to design database applications using data control and ADO
control. However, those applications are very simple and plain . In this lesson, you will learn to create a
more advanced database application using ADO control. The application you are going to create is known
as an electronic library. This electronic library will be able to accept users' registration as well as handling
login command that require the user's password, thus enhancing the security aspect of the database.
Basically, the application will constitute a welcome menu, a registration menu, a Login menu and the main
database menu. The sequence of the menus are illustrated as follow:
First of all, you need to design the Welcome menu. You can follow the example as follow:
In this form, you need to insert three command buttons and set their properties as follow:
If a new user click the Register button, the registration form will appear. An example is illustrated as
follow:
This registration forms consist of two text boxes , three command buttons and an ADO control. Their
properties are set as follow:
note that the PasswordChar of textbox 2 is set as * which means users will not be able to see the actual
characters they enter, they will only see the * symbol.
End Sub
UserInfo.Recordset.Fields("username") = txtName.Text
UserInfo.Recordset.Fields("password") = txtpassword.Text
UserInfo.Recordset.Update
Register.Hide
Login_form.Show
End Sub
There are two text boxes and a command button, their properties are set as follow:
Textbox 1 name txtName
Textbox 2 name txtpassword
Command button 1
cmdLogin
name
Command button 1
Login
Caption
Form name Login_form
Register.UserInfo.Refresh
usrname = txtName.Text
psword = txtpassword.Text
Do Until Register.UserInfo.Recordset.EOF
If Register.UserInfo.Recordset.Fields("username").Value = usrname And
Register.UserInfo.Recordset.Fields("password").Value = psword Then
Login_form.Hide
frmLibrary.Show
Exit Sub
Else
Register.UserInfo.Recordset.MoveNext
End If
Loop
End Sub
End Sub
End Sub
adoLibrary.Recordset.Fields("Title").Value = txtTitle.Text
adoLibrary.Recordset.Fields("Author").Value = txtAuthor.Text
adoLibrary.Recordset.Update
End Sub
Lesson 23 : Animation-Part I
Animation is always an interesting and exciting part of programming. Although visual basic is not
designed to handle advance animations, you can still create some interesting animated effects if you put
in some hard thinking. There are many ways to create animated effects in VB6, but for a start we will
focus on some easy methods.
The simplest way to create animation is to set the VISIBLE property of a group of images or pictures or
even texts and labels to true or false by triggering a set of events such as clicking a button. Let's examine
the following example:
This is a program that create the illusion of moving the jet plane in four directions, North, South ,East,
West. In order to do this, insert five images of the same picture into the form. Set the visible property of
the image in the center to be true while the rest set to false. On start-up, a user will only be able to see
the image in the center. Next, insert four command buttons into the form and change the labels to Move
North, Move East, Move West and Move South respectively. Double click on the move north button and
key in the following procedure:
Sub Command1_click( )
Image1.Visible = False
Image3.Visible = True
Image2.Visible = False
Image4.Visible = False
Image5.Visible = False
End Sub
By clicking on the move north button, image1 and other images except image 3 displayed. This will give
an illusion that the jet plane has moved north. Key in similar procedures by double clicking other
command buttons. You can also insert an addition command button and label it as Reset and key in the
following codes:
Image1.Visible = True
Image3.Visible = False
Image2.Visible = False
Image4.Visible = False
Image5.Visible = False
Clicking on the reset button will make the image in the center visible again while other images become
invisible, this will give the false impression that the jet plane has move back to the original position
You can also issue the commands using a textbox, Another simple way to simulate animation in VB6 is
by using the Left and Top properties of an object.
this idea actually came from my son Liew Xun (10
Image.Left give the distance of the image in twips
years old). His program is shown below: from the left border of the screen, and Image.Top
give the distance of the image in twips from the top
border of the screen, where 1 twip is equivalent to
Private Sub Command1_Click() 1/1440 inch. Using a statement such as Image.Left-
100 will move the image 100 twips to the left,
Image.Left+100 will move the image 100 twip away
If Text1.Text = "n" Then from the left(or 100 twips to the right), Image.Top-100
Image1.Visible = False will move the image 100 twips to the top and
Image.Top+100 will move the image 100 twips away
Image3.Visible = True from the top border (or 100 twips down).Below is a
Image2.Visible = False program that can move an object up, down. left, and
right every time you click on a relevant command
Image4.Visible = False button.
Image5.Visible = False
End Sub
The fourth example let user magnify and diminish an The Codes
object by changing the height and width properties of
an object. It is quite similar to the previous example. Private Sub Command1_Click()
The statements Image1.Height = Image1.Height + Image1.Height = Image1.Height + 100
100 and Image1.Width = Image1.Width + 100 will Image1.Width = Image1.Width + 100
increase the height and the width of an object by 100 End Sub
twips each time a user click on the relevant
command button. On the other hand, The Private Sub Command2_Click()
statements Image1.Height = Image1.Height - 100
and Image1.Width = Image1.Width -100 will Image1.Height = Image1.Height - 100
decrease the height and the width of an object by Image1.Width = Image1.Width - 100
100 twips each time a user click on the relevant
command button End Sub
Drag and drop is a common windows application where you can drag and drop an object such as a file
into a folder or into a recycle bin. This capability can be easily programmed in visual basic. In the
following example, I am creating a simulation of dragging the objects into a recycle bin, then drop a fire
and burn them.
In this program, I put 6 images on the form, one of them is a recycle bin, another is a burning recycle bin ,
one more is the fire, and three more images are to be dragged into the recycle bin. In addition, set the
property dragmode of all the images( including the fire) to be dragged to 1(Automatic) so that dragging is
enabled, and set the visible property of burning recycle bin to false at start-up. Besides, label the tag of
fire as fire in its properties windows. If you want to have better dragging effects, you need to load an
appropriate icon under the dragIcon properties for those images to be dragged, preferably the icon should
be the same as the image so that when you drag the image, it is like you are dragging the image along.
Source refer to the image to be dragged. Using the code Source.Visible=False means it will disappear
after being dragged into the recycle bin(Image4).If the source is Fire, then the recycle bin will changed
into a burning recycle bin , which is accomplished by using the code Image4.Picture = Image5.Picture,
where Image 5 is the burning recycle bin.
For details of this program, please refer to my game and fun programming page or click this link, Recycle
Bin.
24.2 Animation for a complete motion.
So far those examples of animation shown in lesson 23 only involve movement of static images. In this
lesson, you will be able to create true animation where an action finish in a complete cycle, for example, a
butterfly flapping its wings. In the following example, I used eight picture frames of a butterfly which
display a butterfly flapping its wing at different stages.
You can actually copy the above images and use them in your program. You need to put all the above
images overlapping one another, make image1 visible while all other images invisible at start-up. Next,
insert a command button and label it as Animate. Click on the command button and key in the statements
that make the images appear and disappear successively by using the properties image.visible=true and
image.visible=false. I use If..... Then and Elseif to control the program flow. When you run the program,
you should be able to get the following animation.
.
The Codes
End Sub
If you wish to create the effect of the butterfly flapping its wing and flying at the same time, then you could
use the Left and Top properties of an object, such as the one used in the examples of lesson 23. Below is
an example of a subroutine where the butterfly will flap its wing and move up at the same time. You can
also write subroutines that move the butterfly to the left, to the right and to the bottom.
Sub move_up( )
All preceding examples of animation that you have learn in lesson 23 and lesson 24 only involve manual
animation, which means you need to keep on clicking a certain command button or pressing a key to
make an object animate. In order to make it move automatically, you need to use a timer. The first step in
creating automatic animation is to drag the timer from the toolbox into the form and set its interval to a
certain value other than 0. A value of 1 is 1 milliseconds which means a value of 1000 represents 1
second. The value of the timer interval will determine the speed on an animation.
In the following example, I use a very simple technique to show animation by using the properties
Visible=False and Visible=true to show and hide two images alternately. When you click on the program,
you should see the following animation.
The Codes
Private Sub
Timer1_Timer()
If Image1.Visible = True
Then
Image1.Visible = False
Image2.Visible = True
ElseIf Image2.Visible =
True Then
Image2.Visible = False
Image1.Visible = True
End If
End Sub
Next example shows a complete cycle of a motion such as the butterfly flapping its wing. Previous
examples show only manual animation while this example will display an automatic animation once you
start the program or by clicking a command button. Similar to the example under lesson 24.2, you need to
insert a group of eight images of a butterfly flapping its wings at different stages. Next, insert a timer into
the form and set the interval to 10 or any value you like. Remember to make image1 visible while other
images invisible at start-up. Finally, insert a command button, rename its caption as Animate and key in
the following statements by double clicking on this button. Bear in mind that you should enter the
statements for hiding and showing the images under the timer1_timer subroutine otherwise the animation
would work. Clicking on the animate button make timer start ticking and the event will run after every
interval of 10 milliseconds or whatever interval you have set at design time. In future lesson, I will show
you how to adjust the interval at runtime by using a slider bar or a scroll bar. When you run the program,
you should see the following animation:
Private Sub Form_Load() ElseIf Image3.Visible =
Image1.Visible = True True Then
x=0 Image3.Visible = False
End Sub Image4.Visible = True
ElseIf Image4.Visible =
Private Sub True Then
Command1_Click() Image4.Visible = False
Timer1.Enabled = True Image5.Visible = True
End Sub ElseIf Image5.Visible =
True Then
Private Sub Image5.Visible = False
Timer1_Timer() Image6.Visible = True
If Image1.Visible = True ElseIf Image6.Visible =
Then True Then
Image1.Visible = False Image6.Visible = False
Image2.Visible = True Image7.Visible = True
ElseIf Image7.Visible =
ElseIf Image2.Visible = True Then
True Then Image7.Visible = False
Image2.Visible = False Image8.Visible = True
Image3.Visible = True ElseIf Image8.Visible =
True Then
Image8.Visible = False
Image1.Visible = True
End If
End Sub
To design the interface, you need to insert one combo box which will be used to display the URLs. In
addition, you need to insert a few images which will function as command buttons for the user to navigate
the Internet; they are the Go command, the Back command, the Forward command, the Refresh
command and the Home command. You can actually put in the command buttons instead of the images,
but using images will definitely improve the look of the browser.
The procedures for all the commands are relatively easy to write. There are many methods, events, and
properties associated with the web browser but you need to know just a few of them to come up with a
functional Internet browser
The method navigate is to go the website specified by its Uniform Resource Locator(URL). The syntax is
WebBrowser1.Navigate (“URL”). In this program, I want to load the www.vbtutor.net web page at start-up,
so I type in its URL.
In order to show the URL in the combo box and also to display the page title at the form caption after the
page is completely downloaded, I use the following statements:
The following procedure will tell the user to wait while the page is loading.
Inet1 comprises three important properties namely Inet1.URL that is used to identify the FTP hostname,
inet1.UserName that is used to accept the username and the Inet1.Password that is used to accept the
user’s passwords. The statements for the program to read the hostname of the server, the username and
the password entered into Textbox1, Textbox2 and Textbox3 by the user are shown below:
Inet1.URL=Text1.Text
Inet1.UserName=Text2.Text
Inet1.Passoword=Text3.Text
After the user entered the above information, the program will attempt to connect to the server using the
following command, where Execute is the method and DIR is the FTP command that will read the list of
files from the specified directory of the remote computer and you need to use the getChunk method to
actually retrieve the directory’s information.
Inet1.Execute, "DIR
After connecting to the server, you can choose the file from the remote computer to download by
using the statement below:
Inet1.Execute, , "get" & remotefile & localfile
where remotefile is the file of the remote site and localfile is the file of the local system. However, very
often you need to provide the full path of the local file, which you can do that by modifying the above
syntax to the following syntax:
Inet1.Execute , , "get" & remotefile & localpath & remotefile
The above statements will ensure that the remote file will be downloaded to the location specified by the
localpath and the file downloaded will assume the same name as the remote file. For example, the
remote file is readme.txt and the localpath is C:\temp , so the downloaded file will be saved in
C:\temp\readme.txt
In order to monitor the status of the connection, you can use the StateChanged event that is associated
with Inet1 together with a set of the state constants that are listed in the following table.
Option Explicit
After logging in, the main form will be presented as shown in Figure 30.3
Under the StateChanged event, you use the Select Case…End Select statements to notify the users
regarding the various states of the connection. The procedure is shown below:
The FTP program that I have created contains a form and a dialog box. The dialog box can be added by
clicking on the Project item on the menu bar and then selecting the Add Form item on the drop-down list.
You can either choose a normal dialog box or a login dialog box. The function of the dialog box is to
accept the FTP address, the username and the password and then to connect to the server. After
successful login, the dialog box will be hidden and the main form will be presented for the user to browse
the remote directory and to choose certain files to download.