Lesson1 : Introduction
to Visual Basic 6
1.1 The concept of computer programming
Before we begin Visual Basic 6 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.
|
|
Many people think that computer is very intelligent, but in
actual fact it is dumb and can't do anything without human assistance. The
microchips of a CPU can only understand two distinct electrical states,
namely, the on and off states, or 0 and 1 in the binary system. So, the CPU
only understands a combinations of 0 and 1 code, a language which we called
machine language. Machine language is extremely difficult to learn and it is
not for us to master it easily.That's why modern programming languages
supported by web hosting providers, such as PHP, Javascript, etc are
all very high level. They allow us to communicate with the computer using
language we can relate to, rather than machine language.
Fortunately , we have many smart programmers who 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, flash action script, JavaScript, HTMLand
more.
|
1.2
What is Visual Basic?
VISUAL BASIC is a high level programming language which evolved
from the earlier DOS version called BASIC. BASIC means Beginners' All-purpose SymbolicInstruction Code. It is a relatively easy
programming language to learn. The code looks a lot like English
Language. Different software companies produced different versions of BASIC,
such as Microsoft QBASIC, QUICKBASIC, GWBASIC ,IBM BASICA and so on. However,
people prefer to use Microsoft Visual Basic today, as it is a well developed
programming language and supporting resources are available everywhere. Now, there are many versions of VB exist
in the market, the most popular one and still widely used by many VB
programmers is none other than Visual
Basic 6 .
We also have VB.net, Visual Basic 2005, Visual
Basic 2008 and
the latest Visual
Basic 2010 .
Both Vb2008 and VB2010 are fully object oriented programming (OOP) languages.
|
VISUAL BASIC is a VISUAL and Event-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
VB6, programming is done in a graphical environment. In the old BASIC, you
have to write program code for each graphical object you wish to display it
on screen, including its position and its color. However, In VB6 , you just
need to drag and drop any graphical object anywhere on the form, and you can
change its properties using the properties window.
In addition, Visual Basic 6 is Event-driven because we need to write code
in order to perform some tasks in response to certain events. The events
usually comprises but not limited to the user's inputs. Some of the events
are load, click, double click, drag and drop, pressing the keys and more. We
will learn more about events in later lessons. Therefore, a VB6 Program is
made up of many subprograms, each has its own program code, and each can be
executed independently and at the same time each can be linked together in
one way or another.
|
1.3
What programs can you create with Visual Basic 6?
With VB 6, you can create any program depending on your
objective. For example, if you are a college or university lecturer, you
can create educational programs to teach business, mathematics, science,
economics, engineering, computer science, accountancy , financial management,
information system and more to make teaching more effective and interesting.
For example, you can create mathematical programs such as Geometric Progression, Quadratic Equation Solver, Simultaneous Equation Solver ,Prime Number, Factors Finder, Quadratic Function
Graph Plotter and so on. For
science teacher, you can create simulation programs such as Projectile, Simple Harmonic Motion, Star War etc. If you are in business, you can also
create business programs such asinventory
management system , Amortization Calculator , investments calculator,
point-of-sale system, payroll system, accounting program and more to help
manage your business and increase productivity. For those of you who like games
, you can create those programs such as slot machine, reversi, tic tac toeand more.
Besides, you can create multimedia programs such as Smart Audio Player, Multimedia Player
and so on. Indeed, there is no
limit to what program you can create ! There are many such programs in this tutorial,
so you must spend more time on the tutorial in order to learn how to create
those programs.
1.4
The Visual Basic 6 Integrated Development Environment
Before you can program in VB 6, you need to install Visual Basic
6 compiler in your computer. You can purchase a copy of Microsoft
Visual Basic 6.0 Learning Edition or Microsoft
Visual Basic Professional 6.0 with Plus Pack from
Amazon.com, both are vb6 compilers. If you have already installed Microsoft
Office in your PC or laptop, you can also use the built-in Visual
Basic Application in Excel to
start creating Visual Basic programs without having to spend extra cash to buy
the VB6 compiler.
|
After installing vb6 compiler, the icon with appear on your
desktop or in your programs menu. Click on the icon to launch the VB6
compiler. On start up, Visual Basic 6.0 will display the following
dialog box as shown in Figure 1.1.
Figure 1.2: VB6 Programming Environment
Form is the primary building block of a Visual Basic 6
application. A Visual Basic 6 application can actually comprises many forms;
but we shall focus on developing an application with one form first. We will
learn how to develop applications with multiple forms later. Before you
proceed to build the application, it is a good practice to save the project
first. You can save the project by selecting Save Project from
the File menu, assign a name to your project and save it in a
certain folder.
|
Lesson 2: Building
Visual Basic Applications
In the previous chapter, we have learned to use the basic SQL
keywords SELECT and FROM to manipulate database in Visual Basic 6 environment.
In this lesson, you will learn to use more SQL keywords. One of the more
important SQL keywords is WHERE. This keyword allow the user to search for data
that fulfill certain criteria.
|
The Syntax is as follows:
SELECT fieldname1,fieldname2,.....,fieldnameN FROM TableName
WHERE CriteriaThe criteria can be specified using operators such as =, >,<, <=, >=, <> and Like. Using the database books.mdb created in the previous chapter, we will show you a few examples. First of all, start a new project and insert a DataGrid control and an |
|
|
Example 28.1: Query based on Author
Run the program and key in the following SQL query statement
SELECT Title, Author FROM book WHERE Author='Liew Voon Kiong'
Where you click on the query button, the DataGrid will display
the author name Liew Voon Kiong. as shown below:
|
|
Example 28.2:Query based on year
Run the program and key in the following SQL query statement:
SELECT * FROM book WHERE Year>2005
When you click on
the query button, the DataGrid will display all the books that were published
after the year 2005.
You can also try following queries:
- SELECT * FROM
book WHERE Price<=80
- SELECT * FROM
book WHERE Year=2008
- SELECT * FROM
book WHERE Author<>'Liew Voon Kiong'
You may also search for data that contain certain characters by
pattern matching. It involves using the Like operator and the %symbol. For example, if you
want to search for a author name that begins with alphabet J, you can use the
following query statement
SELECT * FROM book WHERE Author Like 'J%'
Where you click on the query command button, the records where
authors' name start with the alphabet J will be displayed, as shown below:
Next, if you wish to rank order the data, either in ascending or
descending order, you can use the ORDER
By , ASC (for ascending) and DESC(Descending) SQL keywords.
The general formats are
SELECT fieldname1, fieldname2.....FROM
table ORDER BY fieldname ASC
SELECT fieldname1, fieldname2.....FROM table ORDER BY fieldname DESC
Example 28.3:
The following query statement will rank the records according to
Author in ascending order.
SELECT Title, Author
FROM book ORDER BY Author ASC
Example 28.4
The following query statement will rank the records according to
price in descending order.
SELECT Title, Price FROM book ORDER BY Price DESC
Lesson 29: Creating
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 how 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 the user 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:
|
|
|
2.1 The Welcome Menu
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:
Propery Name
|
Setting
|
Form name
|
frmMainMenu
|
command button 1 Name
|
cmdRegister
|
command button 1 Caption
|
Register
|
command button 2 Name
|
cmdLogin
|
command button 2 Caption
|
Login
|
command button 3 Name
|
cmdCancel
|
command button 3 Caption
|
Cancel
|
The code is as follows:
Private Sub cmdCancel_Click()
End SubEnd End Sub Private Sub cmdLogin_Click() Me.Hide Login_form.Show End Sub Private Sub cmdRegister_Click() Me.Hide Register.Show |
*using Me.Hide is a better option then using frmMainMenu.Hide
because your program code will be more precise and more readable.
29.2 The Registration Form
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 others will not be able to see the actual
characters entered by the user, they will only see the * symbol.
The code is as follow:
Private Sub cancel_Click( )
adoUserInfo.Recordset.AddNewEnd End Sub Private Sub cmdClear_Click( ) txtName.Text = "" txtpassword.Text = "" End Sub Private Sub cmdConfirm_Click() adoUserInfo.Recordset.Fields("username") = txtName.Text adoUserInfo.Recordset.Fields("password") = txtpassword.Text adoUserInfo.Recordset.Update Me.Hide Login_form.Show End Sub |
|
29.3 The Login Menu
The Login menu is illustrated as follow:
There are two text boxes and a command button, their
properties are set as follow:
Propery Name
|
Setting
|
Textbox 1 name
|
txtName
|
Textbox 2 name
|
txtpassword
|
Command button 1 name
|
cmdLogin
|
Command button 1 Caption
|
Login
|
Form name
|
Login_form
|
The code is as follow:
Private Sub cmdLogin_Click()
Dim usrname As String
Dim psword As String
Dim usernam As String
Dim pssword As String
Dim Msg As String
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
Me.Hide
frmLibrary.Show
Exit Sub
Else
frmRegister.UserInfo.Recordset.MoveNext
End If
Loop
Msg = MsgBox("Invalid password, try again!", vbOKCancel)
If (Msg = 1) Then
Login_form.Show
txtName.Text = ""
txtpassword = ""
Else
End
End If
End Sub
Dim usrname As String
Dim psword As String
Dim usernam As String
Dim pssword As String
Dim Msg As String
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
Me.Hide
frmLibrary.Show
Exit Sub
Else
frmRegister.UserInfo.Recordset.MoveNext
End If
Loop
Msg = MsgBox("Invalid password, try again!", vbOKCancel)
If (Msg = 1) Then
Login_form.Show
txtName.Text = ""
txtpassword = ""
Else
End
End If
End Sub
29.4 The Main Database Manager
The main database manager is illustrated as follow:
The properties of all controls are listed in the table below:
Propert Name
|
Setting
|
Form name
|
frmLibrary
|
|
adoLibrary
|
|
False
|
TextBox 1 name
|
txtTitleA
|
TextBox 2 name
|
txtAuthor
|
TextBox 3name
|
txtPublisher
|
TextBox 4 name
|
txtYear
|
TextBox 5 name
|
txtCategory
|
Command button 1 name
|
cmdSave
|
Command button 1 caption
|
&Save
|
Command button 2 name
|
cmdNew
|
Command button 2 caption
|
&New
|
Command button 3 name
|
cmdDelete
|
Command button 3 caption
|
&Delete
|
Command button 4 name
|
cmdCancel
|
Command button 4 caption
|
&Cancel
|
Command button 5 name
|
cmdNext
|
Command button 5 caption
|
N&ext
|
Command button 6 name
|
cmdPrevious
|
Command button 6 caption
|
&Previous
|
Command button 7 name
|
cmdExit
|
Command button 7 caption
|
E&xit
|
The code is as follow:
Private Sub cmdCancel_Click()
txtTitle.Text = ""
txtAuthor.Text = ""
txtPublisher.Text = ""
txtYear.Text = ""
txtCategory.Text = ""
End Sub
Private Sub cmdDelete_Click()
Confirm = MsgBox("Are you sure you want to delete this record?", vbYesNo, "Deletion Confirmation")
If Confirm = vbYes Then
adoLibrary.Recordset.Delete
MsgBox "Record Deleted!", , "Message"
Else
MsgBox "Record Not Deleted!", , "Message"
End If
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdNew_Click()
adoLibrary.Recordset.AddNew
End Sub
Private Sub cmdNext_Click()
If Not adoLibrary.Recordset.EOF Then
adoLibrary.Recordset.MoveNext
If adoLibrary.Recordset.EOF Then
adoLibrary.Recordset.MovePrevious
End If
End If
End Sub
Private Sub cmdPrevious_Click()
If Not adoLibrary.Recordset.BOF Then
adoLibrary.Recordset.MovePrevious
If adoLibrary.Recordset.BOF Then
adoLibrary.Recordset.MoveNext
End If
End If
End Sub
Private Sub cmdSave_Click()
txtTitle.Text = ""
txtAuthor.Text = ""
txtPublisher.Text = ""
txtYear.Text = ""
txtCategory.Text = ""
End Sub
Private Sub cmdDelete_Click()
Confirm = MsgBox("Are you sure you want to delete this record?", vbYesNo, "Deletion Confirmation")
If Confirm = vbYes Then
adoLibrary.Recordset.Delete
MsgBox "Record Deleted!", , "Message"
Else
MsgBox "Record Not Deleted!", , "Message"
End If
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdNew_Click()
adoLibrary.Recordset.AddNew
End Sub
Private Sub cmdNext_Click()
If Not adoLibrary.Recordset.EOF Then
adoLibrary.Recordset.MoveNext
If adoLibrary.Recordset.EOF Then
adoLibrary.Recordset.MovePrevious
End If
End If
End Sub
Private Sub cmdPrevious_Click()
If Not adoLibrary.Recordset.BOF Then
adoLibrary.Recordset.MovePrevious
If adoLibrary.Recordset.BOF Then
adoLibrary.Recordset.MoveNext
End If
End If
End Sub
Private Sub cmdSave_Click()
adoLibrary.Recordset.Fields("Title").Value =
txtTitle.Text
adoLibrary.Recordset.Fields("Author").Value = txtAuthor.Text
adoLibrary.Recordset.Update
adoLibrary.Recordset.Fields("Author").Value = txtAuthor.Text
adoLibrary.Recordset.Update
End Sub
Lesson 30 :
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 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
End SubImage3.Visible = True Image2.Visible = False Image4.Visible = False Image5.Visible = False |
By clicking on the move north button, only image 3 is 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
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, the code is
shown below:
Private Sub Command1_Click()
If Text1.Text = "n" Then Image1.Visible = False Image3.Visible = True Image2.Visible = False Image4.Visible = False Image5.Visible = False ElseIf Text1.Text = "e" Then Image1.Visible = False Image4.Visible = True Image2.Visible = False Image3.Visible = False Image5.Visible = False ElseIf Text1.Text = "w" Then Image1.Visible = False Image3.Visible = False Image2.Visible = False Image4.Visible = False Image5.Visible = True ElseIf Text1.Text = "s" Then Image1.Visible = False Image3.Visible = False Image2.Visible = True Image4.Visible = False Image5.Visible = False End If
End Sub
|
|
Another simple way to simulate animation in VB6 is by using the
Left and Top properties of an object. Image.Left give the distance of the image
in twips 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 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 from the left(or 100 twips to the right), Image.Top-100 will move the
image 100 twips to the top and Image.Top+100 will move the image 100 twips away
from the top border (or 100 twips down).Below is a program that can move an
object up, down. left, and right every time you click on a relevant command
button.
The Code
Private Sub Command1_Click()
Image1.Top = Image1.Top + 100
End Sub
Private Sub Command2_Click()
Image1.Top = Image1.Top - 100
End Sub
Private Sub Command3_Click()
Image1.Left = Image1.Left + 100
End Sub
Private Sub Command4_Click()
Image1.Left = Image1.Left - 100
End Sub
Private Sub Command1_Click()
Image1.Top = Image1.Top + 100
End Sub
Private Sub Command2_Click()
Image1.Top = Image1.Top - 100
End Sub
Private Sub Command3_Click()
Image1.Left = Image1.Left + 100
End Sub
Private Sub Command4_Click()
Image1.Left = Image1.Left - 100
End Sub
The fourth example let user magnify and diminish an object by
changing the height and width properties of an object. It is quite similar to the
previous example. The statements Image1.Height = Image1.Height +
100 and Image1.Width = Image1.Width + 100 will increase the height and
the width of an object by 100 twips each time a user click on the relevant
command button. On the other hand, The statements Image1.Height =
Image1.Height - 100 and Image1.Width = Image1.Width -100 will decrease
the height and the width of an object by 100 twips each time a user click on
the relevant command button
The Code
Private Sub Command1_Click()
Image1.Height = Image1.Height + 100
Image1.Width = Image1.Width + 100
End Sub
Private Sub Command2_Click()
Image1.Height = Image1.Height - 100
Image1.Width = Image1.Width - 100
End Sub
Image1.Height = Image1.Height + 100
Image1.Width = Image1.Width + 100
End Sub
Private Sub Command2_Click()
Image1.Height = Image1.Height - 100
Image1.Width = Image1.Width - 100
End Sub
You can try to combine both programs above and make an object
move and increases or decreases in size each time a user click a command
button.
Lesson 31: Animation -
Part II
31.1 Animation using a DragDrop Procedure
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 away.
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. In addition, set the property dragmode of all the images( including the fire)
that are 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.
The essential event procedure in this program is as
follows: Private Sub Image4_DragDrop(Source As Control, X As Single, Y As Single)
Source.Visible = False
End SubIf Source.Tag = "Fire" Then Image4.Picture = Image5.Picture End If |
|
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.
31.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 Interface
The Code
Private Sub Command1_Click()
If Image1.Visible = True Then
End SubImage1.Visible = False Image2.Visible = True ElseIf Image2.Visible = True Then Image2.Visible = False Image3.Visible = True ElseIf Image3.Visible = True Then Image3.Visible = False Image4.Visible = True ElseIf Image4.Visible = True Then Image4.Visible = False Image5.Visible = True ElseIf Image5.Visible = True Then Image5.Visible = False Image6.Visible = True ElseIf Image6.Visible = True Then Image6.Visible = False Image7.Visible = True ElseIf Image7.Visible = True Then Image7.Visible = False Image8.Visible = True ElseIf Image8.Visible = True Then Image8.Visible = False Image1.Visible = True End If |
|
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( )
If Image1.Visible = True Then
Image1.Visible = False
Image2.Visible = True
Image2.Top = Image2.Top - 100
ElseIf Image2.Visible = True Then
Image2.Visible = False
Image3.Visible = True
Image3.Top = Image3.Top - 100
ElseIf Image3.Visible = True Then
Image3.Visible = False
Image4.Visible = True
Image4.Top = Image4.Top - 100
ElseIf Image4.Visible = True Then
Image4.Visible = False
Image5.Visible = True
Image5.Top = Image5.Top - 100
ElseIf Image5.Visible = True Then
Image5.Visible = False
Image6.Visible = True
Image6.Top = Image6.Top - 100
ElseIf Image6.Visible = True Then
Image6.Visible = False
Image7.Visible = True
Image7.Top = Image7.Top - 100
ElseIf Image7.Visible = True Then
Image7.Visible = False
Image8.Visible = True
Image8.Top = Image8.Top - 100
ElseIf Image8.Visible = True Then
Image8.Visible = False
Image1.Visible = True
Image1.Top = Image1.Top - 100
End If
Image1.Visible = False
Image2.Visible = True
Image2.Top = Image2.Top - 100
ElseIf Image2.Visible = True Then
Image2.Visible = False
Image3.Visible = True
Image3.Top = Image3.Top - 100
ElseIf Image3.Visible = True Then
Image3.Visible = False
Image4.Visible = True
Image4.Top = Image4.Top - 100
ElseIf Image4.Visible = True Then
Image4.Visible = False
Image5.Visible = True
Image5.Top = Image5.Top - 100
ElseIf Image5.Visible = True Then
Image5.Visible = False
Image6.Visible = True
Image6.Top = Image6.Top - 100
ElseIf Image6.Visible = True Then
Image6.Visible = False
Image7.Visible = True
Image7.Top = Image7.Top - 100
ElseIf Image7.Visible = True Then
Image7.Visible = False
Image8.Visible = True
Image8.Top = Image8.Top - 100
ElseIf Image8.Visible = True Then
Image8.Visible = False
Image1.Visible = True
Image1.Top = Image1.Top - 100
End If
End Sub
Lesson 32: Animation -
Part III
32.1 Animation using Timer
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 Code
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:
|
|
The
Code
Private
Sub Form_Load()
Image1.Visible = True x = 0 End Sub Private Sub Command1_Click() Timer1.Enabled = True End Sub Private Sub Timer1_Timer() If Image1.Visible = True Then Image1.Visible = False Image2.Visible = True ElseIf Image2.Visible = True Then Image2.Visible = False Image3.Visible = True ElseIf Image3.Visible = True Then Image3.Visible = False Image4.Visible = True ElseIf Image4.Visible = True Then Image4.Visible = False Image5.Visible = True ElseIf Image5.Visible = True Then Image5.Visible = False Image6.Visible = True ElseIf Image6.Visible = True Then Image6.Visible = False Image7.Visible = True ElseIf Image7.Visible = True Then Image7.Visible = False Image8.Visible = True ElseIf Image8.Visible = True Then Image8.Visible = False Image1.Visible = True End If End Sub |
|
Please
refer to my fun and games page for more advanced usage of the above animation ,
especially the slotmachine.
Lesson 33: Internet
and Web Applications Part1:
The
Web Browser
If you are bored with existing web browsers, you can create your
very own web browser using Visual Basic. In
order to create the web browser, launch Visual Basic 6, press Ctrl+T to open up
the components window and then select Microsoft
Internet Control. The control
will appear in the toolbox as a small globe. To insert the Microsoft Internet
Control into the form, just drag the globe into the form and a white rectangle
will appear in the form. You can resize this control to the size you wish. This
control is given the default name WebBrowser1.
|
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 Backcommand, the Forward command, the Refresh command and theHome 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 code 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, we want to load the www.vbtutor.net web page at start-up.
The Code
Private Sub Form_Load()
WebBrowser1.Navigate
("http://www.vbtutor.net")
End Sub
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, we use the following statements:
Private
Sub
WebBrowser1_DocumentComplete
(ByVal pDisp As Object, URL As Variant)
Combo1.Text
= URL
Form1.Caption
= WebBrowser1.LocationName
Combo1.AddItem
URL
End
Sub
The following procedure will tell the user to wait while the
page is loading.
Private
Sub
WebBrowser1_DownloadBegin
()
Combo1.Text
= "Page loading, please wait"
End
Sub
|
|
Lesson 34: Internet and Web Applications Part 2:
The
FTP Program
FTP stands for File Transfer Protocol .The File Transfer
Protocol is a system for transferring files between two computers connected by
the Internet .One of the computers is known as the server and the other one is
the client. The FTP program is very useful for website management. The
webmaster can update the web pages by uploading the local files to the web
server easily , at a much faster speed than the web browser. For normal PC
users, the FTP program can also be used to download files from many FTP sites
that offer a lot of useful stuffs such as free software, free games, product
information, applications, tools, utilities, drivers, fixes and many more things.
|
The FTP program usually comprises an interface that shows the
directories of the local computer and the remote server. Files can be
transferred just by clicking the relevant arrows. To log into the FTP site,
we have to enter the user name and the password; however, for public domains,
we just need to type the word anonymous as the user name and you can leave
out the password. The FTP host name takes the form ftp.servername.com, for
example, the Microsoft FTP site’s host name is ftp.microsoft.com
.If you need to use a FTP program, you can purchase one or you can download a
couple of the programs that are available free of charge from the Internet.
However, you can also create your very own FTP program with Visual Basic.
Visual Basic allows you to build a fully functionally FTP program which may
be just as good as the commercial FTP programs.
|
The engine behind is the Microsoft
Internet Transfer Control 6.0 in which you need to insert it into
your form before you can create the FTP program. The name of the Microsoft
Internet Transfer Control 6.0.is Inet and if you only put in one
control, its name will be Inet1.
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 commands, 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, if the remote file
is readme.txtand 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.
Constant
|
Value
|
Description
|
icHostResolvingHost
|
1
|
The control is looking up the IP address of the specified host
computer.
|
icHostResolved
|
2
|
The control successfully found the IP address of the
specified host computer.
|
icConnecting
|
3
|
The control is connecting to the host computer.
|
icConnected
|
4
|
The control successfully connected to the host computer.
|
icRequesting
|
5
|
The control is sending a request to the host computer.
|
icRequestSent
|
6
|
The control successfully sent the request.
|
icReceivingResponse
|
7
|
The control is receiving a response from the host computer.
|
icResponseReceived
|
8
|
The control successfully received a response from the host
computer.
|
icDisconnecting
|
9
|
The control is disconnecting from the host computer.
|
icDisconnected
|
10
|
The control successfully disconnected from the host computer.
|
icError
|
11
|
An error occurred in communicating with the host computer.
|
icResponseCompleted
|
12
|
The request has been completed and all data has been received.
|
Under the StateChanged event, you use the Select Case…End Select
statements to notify the users regarding the various states of the connection.
The code is shown below:
Private Sub
Inet1_StateChanged(
Case icError
MsgBox Inet1.ResponseInfo, ,
"File failed to transfer"
Case icResolvingHost
Label6.Caption =
"Resolving Host"
Case icHostResolved
Label6.Caption = "Host
Resolved"
Case icConnecting
Label6.Caption =
"Connecting Host"
Case icConnected
Label6.Caption = "Host
connected"
Case icReceivingResponse
Label6.Caption =
"Receiving Response"
Case icResponseReceived
Label6.Caption = "Got
Response"
Case icResponseCompleted
Dim data1 As String
Dim data2 As String
MsgBox "Download
Completed"
End Select
End Sub
|
|
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.
The interface of the login dialog is shown on the right.
|
|
The code for the login dialog is,
Option Explicit
Private Sub OKButton_Click()
Inet1.URL = Text1.Text
Inet1.UserName = Text2.Text
Inet1.Password = Text3.Text
Inet1.Execute , "DIR"
Form1.Show
Dialog.Hide
End Sub
Private Sub Inet1_StateChanged(ByVal State
As Integer)
Case icError
MsgBox Inet1.ResponseInfo, , "File
failed to transfer"
Case icResolvingHost
Label6.Caption = "Resolving
Host"
Case icHostResolved
Label6.Caption = "Host
Resolved"
Case icConnecting
Label6.Caption = "Connecting
Host"
Case icConnected
Label6.Caption = "Host
connected"
Case icReceivingResponse
Label6.Caption = "Receiving
Response"
Case icResponseReceived
Label6.Caption = "Got Response"
Case icResponseCompleted
Dim data As String
Dim data1 As String
MsgBox "Transfer Completed"
Do
data1 = Inet1.GetChunk(1024, icString)
data = data & data1
Loop While Len(data1) <> 0
Form1.Text6.Text = data
End Select
End Sub
Private Sub CancelButton_Click()
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
End Sub
retrieve
The statement data1 = Inet1.GetChunk
(1024, icString) is to use the getChunk method to grab information of the
remote directory and then display the files of the directory in Textbox6.
After logging in, the main form will be
presented as shown in the image
below:
Lesson 35: Errors Handling in Visual
Basic
35.1 Introduction
Error handling
is an essential procedure in Visual Basic programming because it can help
make the program error-free. An error-free program can run smoothly and
efficiently, and the user does not have to face all sorts of problems such as
program crash or system hang.
|
Errors often occur due to incorrect input from the user. For
example, the user might make the mistake of attempting to ask the computer to
divide a number by zero which will definitely causes system error. Another
example is the user might enter a text (string) to a box that is designed to
handle only numeric values such as the weight of a person, the computer will
not be able to perform arithmetic calculation for text therefore will create
an error. These errors are known as synchronous errors.
Therefore a good programmer should be more alert to the parts of
program that could trigger errors and should write errors handling code to
help the user in managing the errors. Writing errors handling code should be
considered a good practice for Visual Basic programmers, so do not try to
finish a program fast by omitting the errors handling code. However, there
should not be too many errors handling code in the program as it create
problems for the programmer to maintain and troubleshoot the program later.
|
35.2 Writing the Errors Handling Code
We shall now learn how to write errors handling code in Visual
Basic. The syntax for errors handling is
On Error GoTo program_label
where program_label is the section of code that is
designed by the programmer to handle the error committed by the user. Once an
error is detected, the program will jump to the program_label section for error handling.
Example 35.1: Division by Zero
Private Sub CmdCalculate_Click()
Dim firstNum, secondNum As Double
firstNum = Txt_FirstNumber.Text secondNum = Txt_SecondNumber.Text On Error GoTo error_handler Lbl_Answer.Caption = firstNum / secondNum Exit Sub 'To prevent error handling even the inputs are valid error_handler: Lbl_Answer.Caption = "Error" Lbl_ErrorMsg.Visible = True Lbl_ErrorMsg.Caption = " You attempt to divide a number by zero!Try again!"
End Sub
Private Sub Txt_FirstNumber_GotFocus()
Lbl_ErrorMsg.Visible = False
End Sub
Private Sub Txt_SecondNumber_GotFocus()
Lbl_ErrorMsg.Visible = False
End Sub
|
The Output Window
Explanation:
In this example, you design the interface as above. Name the
first textbox as Txt_FirstNumber and the second textbox as Txt_SecondNumber.
Insert one command button as label it as Calculate. Insert another label and
name it as Lbl_Answer to display the answers. If the user enter 0 in the
second textbox as shown above, the program will jump to the label error_handler, and the error
handling procedure is executed. It will show an error in the Txt_Answer label
and an error message in the Lbl_ErrorMsg label.
Notice that Exit sub after the division. It is important because
it can prevent the program to execute the error_handler code even though the
user does not enter zero in the second textbox.
Lastly, after the error message appeared, the user will click on
the textboxes again. When this occur, the error message will disappear both
from the answer label and error message label. This is achieved by using the
event procedure GotFocus, as shown in the code.
|
Example 35.2: Nested
Error Handling Procedure
By referring to Example 35.1, we need to consider other types of
errors made by the user, such as entering non-numeric inputs like letters.
Therefore, we need to write error handling code for this error too. It should
be put in the first place as soon as the user input something in the textboxes.
And the error handler label error_handler1 for this error should be put after the error_handler2label.
This means the second error handling procedure is nested within the first error handling
procedure. Notice that you have to put an Exit Sub for the second error
handling procedure to prevent to execute the first error handling procedure
again. The code is as follow:
Private Sub CmdCalculate_Click()
Dim firstNum, secondNum As Double
On Error GoTo error_handler1 firstNum = Txt_FirstNumber.Text secondNum = Txt_SecondNumber.Text On Error GoTo error_handler2 Lbl_Answer.Caption = firstNum / secondNum Exit Sub 'To prevent errror handling even the inputs are valid error_handler2: Lbl_Answer.Caption = "Error" Lbl_ErrorMsg.Visible = True Lbl_ErrorMsg.Caption = " You attempt to divide a number by zero!Try again!" Exit Sub error_handler1: Lbl_Answer.Caption = "Error" Lbl_ErrorMsg.Visible = True Lbl_ErrorMsg.Caption = " You are not entering a number! Try again!"
End Sub
Private Sub Txt_FirstNumber_GotFocus()
Lbl_ErrorMsg.Visible = False
End Sub
Private Sub Txt_SecondNumber_GotFocus()
Lbl_ErrorMsg.Visible = False
End Sub
|
|
The Output window
Lesson 36: Compiling and Distributing
Your Programs
36.1 Compiling your Visual Basic Program
Once your have completed a VB program, you can compile the
program to run as a standalone windows application, without having to launch
the Visual Basic IDE. However, before you compile your program, you have to
debug your program to make sure it is errors free. Once the program is compiled
into an EXE file (executable file), you can not debug it anymore. If you wish
to do so, you have to correct the errors and recompile it.
|
To start compiling your program, click on the menu File and
select Make Project1.exe, as show in Figure 36.1. When you click on Make
Project1.exe , the Make Project dialog box will appear, as shown in Figure
36.2. In this dialog box, assign a file name to this project and save it in the
folder chosen by you. After clicking the OK button, the project properties
dialog will appear where you can select the project you wish to compile, as
shown in Fgure 36.3. In this example, the project we chose to compile is
reversi. The option button in this dialog box let you customize the program
you are going to compile. For example, you can enter the title of the program
, the program's version and your company name. Clicking on the compile tab
will let you decide the kind of code you wish to compile, as shown in
Figure 36.4. The default option is native code and it is the best option
because it normally runs faster. It requires fewer files to run, particular
the VB DLL files. Once you have done that, you can click the OK button to
compile the program. Now you program can run as a standalone application. You
can start your program without launching the Visual Basic IDE.
|
Figure 36.1
|
Figure 36.2
|
|
Figure
36.3
|
Figure
36.4
|
|
36.2 Distributing Your Programs
After successfully created a VB program, you might want to
market your product, either online or offline. This means that you need to
create a package that can be distributed to your potential customers. The
package created can be distributed using CD ROM, DVDROM or the Internet. The
package will allow the user to install the program to install in the computer
with the standard setup routine.
To create the distributable package, you can use the Package and
Development Wizard that came with Visual Basic 6. The main purpose of this
wizard is to create a setup program that can be used to install the
application. Off course, it also does many other jobs like compiling your
application and compresses the files for easy distribution.
When you start the Package and Development Wizard, you will be
presented with the following dialog box:
|
|
First of all, you need to select the project you want to
package. Here we have selected the starwar.vbp project. Next, you need to
select one of the three options. Here, I suggest you select the first option to
let the wizard create the installation package for you to distribute it
using CD ROM or the Internet.
Once you click the package option, you will see the following
dialog box where you are asked to choose a packaging script:
After clicking the next button, you
will see the following dialog box where you will be asked to choose a packaging
type. Normally we choose the Standard Setup Package.
The next dialog box that shows up will ask you where to store
the package, as shown below:
|
|
The next dialog box will show you the files that will be
included in the package.
When you click the Finish button, the package will be created
and ready for distribution. Here is the packaged files for the starwar program
for download at
You must download all the three files into a
folder and then run the setup program.
No comments:
Post a Comment