Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 45

VISUAL BASIC 6..

A HAND BOOK
Visual Basic 6 ..Programming with Visual Studio 6
This article try to help beginners of 'Visual Basic' and
try to deliver a complete VB6 Bible. I use simplest
method to describe each section. Also include some
advanced programming tutorial too.I welcome all type
of suggestions from all sides to make this book
outstanding. I think both teachers and students will
accept this article with full mind. I also welcome those
who would like co-authoring with me..
Contents

• An introduction to Visual Basic


• Basic Features of Visual Basic
• IDE Features of Visual Basic
• Declaring and using Variables
• Work with variables
• Control structures in Visual Basic
• Event driven programming under Windows Platform
• Comments/Documentation
• Understanding and creating Visual Basic Project.
• Advance Visual Basic Programming

An introduction to Visual Basic


Microsoft Windows Operating is the world’s largest using computer operating
system today. Because of its user friendly features and its ability to customize it
became No 1.

Microsoft Visual studio is the programming solution is a power full tool for
developing new packages under Windows platform.

Visual studio Provide many language under this package, Visual Basic was the
simplest among them. Visual Basic as the extension of BASIC language, which
was support only CUI interface (Like Command Mode, Disc Operating
System).This interface has changed into a new interface called GUI. It has many
advantages over CUI and allows users to develop smart applications using Text
boxes, list boxes etc. Visual Basic is a powerful programming system that allows
us to create application that fully makes use of facilities of Graphical User
interface (GUI).

Visual Basic programming system is a window based productivity tool. It


supports an event Driven programming model rather than conventional
procedure oriented model. It provides a rapid application environment, a rich set
of easy to use debugging tools.

How it works

In traditional applications, the application itself controls which portion of code execute
and in what sequence. Execution starts with the first line of the code and follows a
predefined path through the application, calling procedure as needed.

Visual Basic applications are event driven. In an event driven application, the
code doesn’t follow a predefined path, it execute different code sections in
response to events.

Events can be triggered by the user’s actions by messages from the system or
other applications or event from the application itself. The sequence of these
events determines the sequence in which the code executes, thus the path
through the application’s code differs each time the program runs.

With most languages, if you make a mistake in composing your code the error is
caught by the compiler when you start to compile your application. You must
then find and fix the errors and begin the compile cycle again, repeating the
process for each error you found. In Visual Basic VB interprets your code as enter
it, catching and highlighting most syntax or spelling error on the fly. It much likes
an expert’s eye over your shoulder as move through the codes.

In addition to this advanced error handling techniques, Visual Basic also


partially compile the code as it is entered. When you are ready to rub the
program, it takes only small amount of time to finish the compilation. If the
compiler find s and error, it is highlighted and you can make correction and
continue running the program, in short you need not go through the compilation
cycle again.
Visual Basic IDE

Basic Features of Visual Basic


Visual Basic supports following features

1. Data Access Features: this allows programmers to develop database front end
applications and server side components for most popular database formats including MS
SQL and other Databases.
2. Active X Technologies: that allows programmers to use the functionality provided
by other applications, such as MS Office [Word, Excel etc) and other windows
applications. You can even automate applications and objects created using the
professional or Enterprise editions of Visual Basic.
3. Internet capabilities make it easy to provide access to documents and applications
across internet server applications.
4. Your finished application is a true executable (.exe) file that use a visual Basic
Virtual Machine that you can freely distribute.

IDE Features of Visual Basic


Visual Basic posses a Integrated Development Environment [IDE] in which
users can develop, run and debug their applications. Visual basic is a ‘front end’
which is used for design a screen [Called form] and also writing codes for the
specific controls.

There are different type applications we can develop with visual basic enterprise
edition. These types are referred as Projects; in visual basic we create projects
which include different types of modules and many forms. A good project may
have many forms as it can have. Following are the major type of projects we can
have in Visual Basic

1. Standard Exe: A standard EXE project is a typical application in which we can


use the database manipulation.

2. Active EXE, Active DLL: These types of project are available with the
professional edition. Active X components are basic code building components
that don’t have a visible interface and that can add special functionality to our
applications.

3. Active X Control: Using this type of project we can create our own Visual
Basic controls.

4. Active X Document EXE, Active X Document EXE: Active X


Documents are in essence Visual Basic applications that can run in the
environment of container that supports hyper linking, such as internet explorer.

5. Data Project: it is identical to the Standard EXE project type, but it


automatically adds the controls that are used in accessing database to the tool
box. Ti also adds the database Active X Designer to the project explorer window.
Active X Designers are Visual tools for accessing and manipulating databases and
generating reports.

6. DHTML Applications: Using this project user can be developing web


pages that can be displayed in the browser’s window on the client computer.

7. IIS Applications: Visual Basic allows user to build application that run on
the web server and interact with clients over the internet with the internet
information server.

8. Add-in: We can create our own add-in for the VB IDE. Add-ins is the
special commands we can add to Visual Basic menus. Add-ins helps us to extend
the VB IDE.
New Project Dialog Box

VB IDE Windows and Components

From the New Project window we can select one type of project (We already
mentioned different types of VB Projects we can create). The window have three tabs
namely, New, Existing, Recent. The New Window Display the options to start New
Project. The items in this window is Standard EXE, Active X EXE, Active X DLL , Active
X Control, VB Application Wizard, AddIn, Active X Document EXE, Active X Document
DLL. The next tab shows Options to open existing projects and the last tabs show help
you to find recently worked project or the recent created programs.

By Selecting Our First Standard EXE Project we can move to the window as shown
below. This is the main IDE window of Visual Basic. You can see the form in the design
section, in which you can design your application by using the items of tool box.
Tool Box:

Items of tool box are used to design the application interface. These items are called as
Controls. Controls are basically .OCX files. You can add additional controls to tool box
using Project –Components or by Pressing Ctrl + T.

The tools box contains Label, Text box, Picture Box, Image, List Box, Combo Box,
Option Button, Dir List Box etc. To place a control on the form first select the control
with the help of mouse and move mouse over the form. When the mouse is on the form,
the curser turned into a ‘+’ and we can draw the control on the form just as drawing a
rectangle in MS Paint. The items of tools box arranged in ‘General’ Tab, you can re
arrange controls in separate tabs by creating custom tabs by right click the Tool Box. Use
Drag and drop to add the items to Tabs.

The default items available on the tools box are:

1. Label: This control displays a text on the form that the user can’t edit. Labels are
commonly used to identify the controls. The label box can be identified by a name
by setting a name property (this can be done at design time only). The text in the
label control can be change by changing the caption property.
2. Text Box: This control displays the text that the user can edit.
3. Frame: This control is used to draw boxes on the form and group other
elements.
4. Command button: The most common element of windows interface was
command button. A command button represents an action that carries out
when the user click the button.
5. Check box control represents one or more choice that the user can
select. One of the important property of ‘Check box’ control is ‘Value’. If
the check box is marked it will be ‘1’ other wise it will be ‘0’.
6. Option button: Option Buttons/Radio Buttons appears in a group, and
the user can choose only one of them. It’s ‘Value’ Property will be True if it
is selected. Other wise it will be false.
7. List Box: This contains a list of options from which user can choose one
more items. [In windows the Font List box is an example of the use of
list box.]. The Selected item in a ListBox is given by the Text property the
control meanwhile sorted property determines whether the items in the
list box will be sorted or not.
8. ComboBox: This control is similar to the ListBox, but it contains a Text/
Edit field. The user can either select an item from the list or enter a new
string in Edit field. The item selected from the list given by the control’s
TextProperty.
9. Timer: When we need to perform tasks at regular interval we can make
use of Timer. The main property of Timer Control is Interval,
determines how often the timer notifies our application.
10. Picture Box: This control is used to display images and images set with
Picture property. The Picture Box control also supports few functionality
of generating advanced drawing.
11. Shape: This control is used to draw graphical elements such as boxes, and
circles etc.
12. Image: This one is similar to Picture Box but it support less functionality
and make use of less resources.
13. Line: Help use to draw a line.
14. Data: Data Control provides point add click access to data stored in
database [DBMS]. It was the simplest way to access Data Base.
15. OLE: It is a window you can place on the Form to host documents from
other applications. Through this control we can access the functionality of
other applications within our application, if they support OLE feature.
16. File System Controls: These are set of controls which help us to add file
handling capabilities to out program. They are sued together to provide an
interface for accessing and exploring drives, folders and files. The file
system controls are as follows

1) Drive List Box: Used to display the drives on the system in a drop down list
which the user can select.

2) Directory List Box: Used to Display all Folders in current Drive and lets the
use move up and down through the hierarchy of the folders.
3) File List Box: This control displays a list of files in the current folder.

These are important controls even though there are plenty of controls used in
VB. Lots to we will learn more about the property, in details.

Property Window

Properties are the attribute of controls. Every object has properties, for example a Pen,
has its Color, Metal Type,

Ink Color, Type etc. In the same manner every control in VB has many properties. By
using the property fields in property box we can change appearance, text / values
displayed in the controls, the manner in which it look like etc. Some properties are read
only, which means that they can to change at design time only, the values of such
properties can’t change using code, while others are Read and Write. You can move
Property window any side of VB IDE Window, can invoke using tool bar or by Pressing
F4.

Project Explorer

Project explorer displays Opened project and other project components such as Classes
and Modules. We can start multiple projects at the same time; you have to select the
project you want to work with by selecting ‘Set as Start Up’. The project explorer has
three Buttons on the Top of the window, namely View Object, View Code (F7), Toggle
Folder. The first two used to move between Code Window and Form Designer. The third
button helps you to change the listing style of Project Explorer. We can add Multiple
Forms [SDI & MDI] and as many modules and classes we needed.

Form Layout

Form Layout Window is used to arrange the position of form while running the program.

Form Designer

The form designer is the main window in the middle of the screen, in which we can
design and edit user interface. The same window displays a text editor in which we can
enter and edit applications code. The form designer displays two windows, the form it
self and the code window. Select the form you want to view in the project explorer, and
then click one of two view buttons to see form or its code.

VB Editor/ Code Window

In Visual Basic, the editor is called code window, it is actually a turbo charged text editor
with many productivity tool built in. we can open the code window by double clicking a
form or control in the form. If we double click a form we will be taken into procedure for
that control. Once the code window is open, we can go to any procedure for any object on
the selected form.

Object Browser

Object browser allows us to browse through the Various Properties events and methods
that are made available or exposed. We can access it by selecting object browser from the
view menu or by pressing F2.

Declaring and using Variables


A variable is a name given to a location in Random Access Memory (RAM) where
a data value is stored temporarily. The contents of the variable will lost when the
program is ended, we can also alter values stored in a variable during life time of
the program. Visual basic Variables can store string of Text, numbers, objects,
Boolean values etc. for efficiency in sorting and using data visual basic provides a
data type that store specific type of data.

Data Types and their Range

Data Types Storage Size Range of Variables


Byte 1 byte 0 to 255
Boolean 2 bytes True or False
Integer 2 bytes -32,769 to 32,767
Long 4 bytes -2,147,488,648 to 2,147,488,647
Single 4 bytes 7 digits
Double 8 bytes 14 digits
Currency 8 bytes 4 decimal place
String 10 bytes 0 to approximately 2 billion
Object 4 bytes Any object reference
Variant(With 16 bytes Any numeric value up to a range
number) of Doubles.

Syntax: - Dim <variable name> As <DtaType>

Before we make use of variables we need to declare first, in general case. The
naming convention is that, name of variables

• Begin with letter


• Can’t contain an embedded period or embedded type declaration character.
• Must not exceed 255 characters
• Must be unique with in the scope, which is the range from which the
variable can
referenced a procedure, a form, so on

We can mix characters and numbers together. We make use of key words ‘DIM’
and ‘AS’ to declare a variable.

Visual Basic has two types of variable declarations

1) Explicit declaration and

*Place ‘Option explicit’ statement in the declaration section of a Form,


Class, or

Modules

2) Implicit declaration.

In the first we use a statement to define the Data Type of the variable. The
statement does not assign a value to the variable but merely tell visual basic what
values it can contain.

Example: - Dim name As String

Variable declared without type is called implicit declaration. These are called
variants, i.e. we can store any desired value in it.
Example: - Dim Str

Str =1001

Str =”GTEC”

Scope of Variables

Variables are not necessarily available through out the entire program. Their use
can be localized to certain parts of the program only. Localizing in this variable is
a part of good programming practice. The parts of program in which a variable
can use is termed as ‘scope of the variable’. Global variable or Public variables
can be declared in General section of the of the Form. Variable declared in the
sub program or Functions are local (Private) to that Sub program or Function
only.

Module Scope Variables

Visual Basic also has module scope variables which are declared in the general
section of a Code Module. Module scope variables available through out all the
procedure in that Module and not in other modules/Form (if you want to do so,
you must use the keyword ‘Public’ to declare them).You can create module level
variables by declaring them with the Private keyword in the declaration section
at the top of the Module. They can be accessed by procedures and functions in
that module.

Note: -You can’t declare public variables within a procedure, only within the
Declaration section of a module.

Class Module Variables

There is another important variable concerning local variable, they only exist
within the Class Module. Class module has limited access to the variable, they can
only access by means of the object/ variables of that class.

Static Variables

In addition to scope, variables have life time, the period of time during which
they retain their value. The values in module-level and public variables are
preserved for the lifetime of your application. However, local variables declared
with Dim exist only while the procedure in which they are declared is executing.
Usually, when a procedure is finished executing, the values of its local variables
are not preserved and the memory used by the local variables are not preserve
and the memory used by the local variables is declared. The next time the
procedure is executed; all its local variables are reinitialized.
However, you can preserve the value of a local variable by making the variable
‘static’. By using the ‘Static’ keyword to declare one or more variables inside a
procedure, exactly as you would with the ‘Dim’ statement.

*Preserve values even when the procedure, using the Static Variable is ended.

Constants

Often you will find that your code contains a constant value that reappears over
and over. Or you may find that code depends on certain number that are difficult
to remember numbers that, in and of them have no oblivious meaning.

In this case, you can greatly improve the readability of your code and make it
easier to maintain-by using constants. A constant is a meaning full name that
takes the place of a number or string that does not change. Although a constant
somewhat resembles a variable, you can’t modify a constant, or assign a new
value to it as you can to a variable. There are two sources for constants.

1. Intrinsic Constants: which are provided by application and controls. Other


application like MS Office also provides a list of constants you can use with their
object, method, properties. Constants are also defined in the object library for
each Active X Control.
2. Symbolic or User defined Constants: By make use of the keyword ‘Const’
you Can create constants of any type.
Eg: Const pa = 1233

Data Conversion

As we know variables are used to store manipulate data we handle with the pro
program we build. There are occasions that we are convert data into another Data
Type. Here is a list of inbuilt function to do the job.

Function Convert An Expression to


Cbool Boolean
Cbyte Byte
Ccur Currency
Cdate Date
CDbl Double
Cint Integer
CLng Long
CSng Single
CStr String
CVar Variant
CVErr Error
Work with variables
Now we know different type of projects and how to variables and objects. Lets
start our first variable projects.

Q) Read Principle Amount, Interest Rate, Term [Period] and


calculate Interestamont and Net amount.

1. Start Standard EXE Project


2. Double Click the Form to reach the Code Window or press ‘F7’.
3. Then locate General Section from the Drop Down list box that appear top of
the code window[Left Side]
4. Type the following code

Dim Amount As Integer


Dim Irate As Integer
Dim Term As Double
Dim Iamount
Dim Net
5. U can use comment section to Describe the code as follows in any part of
the code window
‘ This program calculate Simple Interest
6. Now we need to Read and manipulate the values. Add following codes to
Click Event of Form, [Select the Click event from the Next list box from the Right
side of the code window].

Private Sub Form_Click()

Net=0 ‘ Empty Values in Variables… (Initializing Zero Values to

Variables)

Iamount=0

Amount=InputBox (“Enter Principle Amount”,”Variable Test”)

Irate= InputBox (“Enter Interest Rate”,”Variable Test”)

Term= InputBox (“Enter Term/Period”,”Variable Test”)


Iamout=Irate*Amount/100*Term

Net=Iamount+Amount

Print “ Amount”,Iamout

Print “Net amount”, Net

End Sub

7. Now Ready to Test the project


8. Press F5 or Find Start Button from Tool Bar / Run Menu

*Here ‘InputBox’ is used to Input Values, it has two arguments first one is its
message and second is Optional title, and i.e. u can avoid it. U can also leave the
argument by inserting “ “.

*’Print’ is used to display values to Form.

Exercise:

1. Read Two Numbers and do Basic Calculations (+, -, *, /)?

* Remember First think of variables and their type, you need to create.

* If u has to display decimal points use Data Types like Double

2. Read a number and fin Cube(x3)?

3. Solve the equation (a+b)2?

Control structures in Visual Basic


A control structure allows you to control the flow of your program’s execution. If
left unchecked by control-flow statements, a program’s logic will flow through
statement from left to right and right to bottom. While some very simple
programs can be written with only this unidirectional flow, and while some flow
can be controlled by using operators to regulate precedence of operations, most
of the power and utility of nay programming language comes from its ability to
change statement order with structures and loops.

Decision Making Statements


Decision making statements useful when we need to evaluate particular
conditions and divert the execution of the program in another path/flow.

VB support two decision making statements

If……Then...…else……End if

If…. Then..…else If…..End If

Select case…..…End Select

If……Then...…else……End if

Synax: If (Condition) Then

<True Block Statements>

Else

<False Block Statements>

End if

If…. Then..…else If…..End If

Synax:

If (Condition) Then

<True Block Statements>

Else If <Condition> Then

<True Block Statements>

Else

<False Block Statements>


End if

Select Case
Sintax:

Select Case(Expression)

Case :Value1

Statement1

Case :Value 2

Statement 2

.......................

.......................

Case Else

Statement

End Select.

The Select Case structure compares one expression to different values. The
Select Case structure tests a single expression which is evaluated once at the top
of the structure. The result of the test is then compare with several values and if it
matches one of the corresponding block of statement is executed. The block of
Case Else statement is optional and is executed non of of the previous Case
Values match the expression.

Event driven programming under Windows Platform


As we know, Visual Basic is a vent driven programming laguage.
Program responds to specific action known as Events. An Event is any
action performing by using any of input devices, primarily mouse ad
keyboard. When we click on specific buttons and menus, action was
fired.
For the easy handling of these events, Visual Basic uses events
procedures.(Later we will discuss about different type of procedures) Visual
Basic System creates event procedures. We can add code/commands that are
meant to execute.

“Envent Driven programming carries many advantages over conventional


programming techniques. The first one is its ease of use and manipulates data in
many ways.”

For the best practice of event programming, we need to understand some basic
events.

Form is the container of other controls that are available in the Tool Box

Lets check out few of the important events of Form

1. Load….Load event occure when for loaded to the screen.

2. Click….Event occures when user click on the form

3. Activate…. This event occure when we make use of the form

4. Initialize….. is triggered just before Load Event

Comments/Documentation
Comments are the none executable sections of the programm. We can use this
facility to add descriptions of code or block specific areas of the code.

We can use a ‘ (Single quote) to comment a section of the code. It can be


appeared any place on the code window, no matter it is within the Event
procedure or within General Section.

For example:

Private Sub Form1_Click ()

‘Display a String to Text Box Control

Text1.Tex = ”Welcome to Knol”

End sub

Understanding and creating Visual Basic


Project.
Under Visual Basic, we are creating programes as a project. Aproject
has many components like Forms, Resource Files, Modules and Class
Modules. These components can be seen on Project Explorer. The
extension of the Visual Basic Project file is .vbp.

Design following Program using the Text Box Control, Label and Command
Button.

Now lets add following code in the OK button's Click event.This will calculate
the total

Private Sub OkBtn_Click()

Text3.Text=Val(Text1.Text)*Val(Text2.Text)

End Sub

In a Text Box Control all data you entered is treated as string. So that we use
function Val() to convert it to Integer Value.
*The Text property of Text Box return/bring the input text.

In the Clear Button's Click Event we need yo add necessary codes to clear the
Boxes.

Private Sub OkBtn_Click()


'*************************************
' Sample Documentation
' This Section Clear the Field
' ************************************

Text1.Text=""
Text3.Text=""
Text3.Text=""

End Sub

Now You are ready to test your first project. Press F5

Remember we can programmed same thing in different ways as the programmer


wish to do things.

1 Build a Simple Image Viewer

To Build a Simple Image Viewer Program we need a Image,Drive List,Directory


List,File List,Label and List Controls.
Image and Picture Controls area common in nature. Both of them have Picture property
which is used to load picture to the control.In Picture control you can see that the picture
is appeared in its actual size at the same time the Image control lets wrap it to the control
with help of Stretch Property, Image also support some additional drawing functions..
Both the controls have a methods called LoadPicture which help us to load a specific file,
all we have to do is specify the path of that picture to be shown.

Label: Label control is used to display a text. It can't be used to input value.It's main
property is Caption, which display text given.
Drive List,Directory List,File List : These Controls work as a batch, i.e, they are meant to
work together.
Frame Control is use to group controls, so that we can move them together.We change
the caption property
to "Select a File".

Arrange these controls as shown below.

1. Now Set Stretch property of Image box to True.


2. Add a label control just above the File List control and set it's caption as "File
Type"
3. Add codes to show Directories and files in selected file and folders.

Const Title = "Picture Viewer 1.1" ' Create a constant called Title.

Private Sub Drive1_Change()


On Error GoTo Error1:
Dir1.Path = Drive1 ' Display all directories in
Selected Drives.
Exit Sub
Error1:
MsgBox "Device Not Found"
End Sub

Private Sub Dir1_Change()


File1.Path = Dir1.Path ' Displays files in the Selected
Folders
End Sub

Private Sub File1_Click()


Image1.Picture = LoadPicture(File1.Path & "\" & File1.FileName)
Form1.Caption = Title & "/" & File1.Name
End Sub

Private Sub Form_Load()


List1.AddItem "*.bmp"
List1.AddItem "*.jpg"
List1.AddItem "*.gif"
End Sub

Private Sub List1_Click()


File1.Pattern = List1.Text
End Sub

Now you are ready to test your application. You can change the icon of
the form.
2 Creating a calculator

*Understanding control array.


In Visual Basic, we can use copies of one control instance, and they act as a group, They
are also called as 'Control array'. Let us build calculator.
First up all we need 9 buttons for showing the Digits (0-9).

1. Insert a button and size it and copy the control and paste, when the system
prompt for Yes or No, Click on the Yes button.
2. Next we need 4 more buttons(array of controls) for Operation
handling(Such as +,-,x,/),

Insert a button and copy paste, 3 times.

1. Last, we need four more buttons (not array/copy) for “=”, ON, OFF, CE
functionality and add a text box.

Now you are ready for coding.

Declare variables first in the General section.

Dim x, y As Integer

Dim optr As String

1. Add following codes in the Click Event of CommandButton 1 (code


window). Hit F7 to invoke the code window.
Private Sub Command1_Click(index As Integer)

'These codes take necessary action to display the inserted value into the Text box. Since
the Buttons are 'array, we only need a single line of code.

Text1.Text = Text1.Text & index

End Sub

This section store information regarding the operations required by the user and it store
details as a string to variable 'optr', so that we can make use of it in the next section.

Private Sub Command2_Click(index As Integer)

Select Case (index)

Case 0

optr = "+"

Case 1

optr = "-"

Case 2

optr = "*"

Case 3

optr = "/"
End Select

'Store value into variables and clear the text box.

x = Val(Text1.Text)

Text1.Text = ""

End Sub

Now we are ready for the operations.All we need is to check optr variable put
necessary operation and set the out put to the text box. Add following codes to
the equalto(=) button's Click Event.

Private Sub Command3_Click()

y = Val(Text1.Text)

Select Case (optr)

Case "+"

z=x+y

Case "-"

z=x-y

Case "*"

z=x*y

Case "/"

z=x/y

End Select

Text1.Text = z

End Sub

The following code


add ON & OFF functionality to the program. All we need is to disable and enable
controls, we are using. For this purpose we used the loop structure since we are
using two control arrays it become simple.

Private Sub Command4_Click()

This section ON the calculator.

For i = 0 To Command1.UBound

Command1.Item(i).Enabled = True

Next i

For i = 0 To Command2.UBound

Command2.Item(i).Enabled = True

Next

Command3.Enabled = True

Text1.Enabled = True

End Sub
Now you are ready to run your Calculator.

Note:

1. You can change your Programs icon and caption as you like.

2. Making your project a complete stand alone application require one more
step.

Go to File->Make and enter name for it. Now the application is a stand alone

calculator, which means that it doesn't need VB to run the application.

3. Create a thumb nail viewer of images.(Understanding control array )

As we already learned control array is the copy of a control. Here we are going to
experiment with the File system controls and image box as control array.
1. First we need to Draw Drive List box, Directory List box and file
list box
2. Set the File List Box’s Pattern property as “*.jpg” to avoid accidental
loading of files
3. Add an image box and copy paste the box 29 time or as much you need
4. Add a list box control, in which we are going to add different picture file
types/ extensions and a command button
5. Add following codes to Drive list box , Directory list boxes.
6. Set Visible property of File1 to False(Hide it)

Private Sub Dir1_Change()

File1.Path = Dir1.Path

End Sub

Private Sub Drive1_Change()

On Error GoTo tt:

Dir1.Path = Drive1

Exit Sub

tt:

MsgBox "The divice cannot acces"


End Sub

7 .Add following codes to form’s load event.

Private Sub Form_Load()

List1.AddItem "*.jpg"

List1.AddItem "*.bmp"

List1.AddItem "*gif"

Drive1 = "E:\" ‘set initial drive

Dir1.Path = "unni" ‘ set initial directory

Image1.Stretch = True ‘resize the picture for image box.

End Sub

8. Add following code to the list box click event, it take necessary action when
you select file type from the list box and reset pattern property of the File list
box.

Private Sub List1_Click()

File1.Pattern = List1.Text

End Sub

9. Now it is time to Load thumbnail views . To do this we use the image box
array. Since it is an array we can use some looping structure.

Add following codes to Command Button’s click Event


Private Sub Command1_Click()

Dim I, C As Integer

C = File1.ListCount

MsgBox C

If C > 29 Then

C = 29

End If

It also checks the count of the files, which not be greater than that of no of image
boxes. If it exceed we need to reset the value

For I = 0 To C

File1.ListIndex = I

Image1.Item(I) = LoadPicture(Dir1.Path & "" & "/" & File1.FileName)


Next

End Sub

10 . We also need an additional Form which we can View picture. Add a image
box to it and set stretch property value to true.On the first form , Double click
on the image box(array) and add following code to display clicked Picture.

Private Sub Image1_DblClick(Index As Integer)

Form2.Show

Form2.Image1.Picture = Image1.Item(Index).Picture

End Sub

11 .Add code to display file location as tool tip of the thumb view.

Private Sub Image1_MouseMove(Index As Integer, Button As


Integer, Shift As Integer,
X As Single, Y As Single)

Image1.Item(Index).ToolTipText = Dir1.Path & File1.FileName

End Sub

Now you can test your project

Note: Remember to double click the folder

4 . Work with Variable ... Some Basic Variable Operations

Following program will help you to learn more about variables and help you to
understand how can we control flow of the variable using ' decision making ...
statements'.
This program will read Name ,Qualification and Mark secured. and also calculate index
mark according to the option user using.

1. Create a form as follows (Use Text Boxes, Combo Box, Option buttons,
Labels and check boxes) and declare following variables in the General section So
as we can access them through out all part of the form.
2. Dim indx, tot As Integer
3. In the load event of the form we should add some values to the combo box

Private Sub Form_Load()


Combo1.AddItem "100"
Combo1.AddItem "1000"
Combo1.AddItem "800"
End Sub

1. Add following codes to the Command Buttons Click event.

'This will calculate the index mark


Private Sub Command1_Click()
'NCC - 15
'NSS - 20
'ARTS - 10
'OTHERS - 5
'SPORTS - 15
' R Cross - 5
Check Box have three values 0,1,2 , 0 means unchecked,1 means checked and 2 for
grayed

If Check1.Value = 1 Then
indx = 10
ElseIf Check2.Value = 1 Then
indx = 15
ElseIf Check3.Value = 1 Then
indx = 5
ElseIf Check1.Value = 1 And Check2.Value = 1 And Check3.Value = 1 Then
indx = 10 + 15 + 5
End If
As for the Check box , option too have a Value property which have only two value
True/False
If Option1.Value = True Then
indx = indx + 20
ElseIf Option2.Value = True Then
indx = indx + 15
ElseIf Option3.Value = True Then
indx = indx + 5
End If

Text5.Text = indx
Text6.Text = indx + Val(Text3.Text) Val() Covert a text to number

End Sub
3. Following code will find the percentage of mark. This can be achieved through the
Click event of the
Combo box.

Private Sub Combo1_Click()


Text4.Text = Val(Text3.Text) / Val(Combo1.Text) * 100
End Sub

4. Some key press event will make this program more comfortable. Let's know how can
we achieve this.

Private Sub Text1_KeyPress(KeyAscii As Integer)


If KeyAscii = 13 Then
Text1.Text = UCase(Text1.Text)
Text2.SetFocus This will set the focus to the TextBox 2
End If
End Sub

Private Sub Text2_KeyPress(KeyAscii As Integer)


If KeyAscii = 13 Then
Text2.Text = UCase(Text2.Text) Convert the text to Upper Case and store again it to
Text Box
Text3.SetFocus
End If
End Sub
' 13 is the key value for the Enter Key, so this event will be triggered when we hit the enter key.
Private Sub Text3_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then
Text3.Text = LTrim(Text3.Text) This will cut all space before the text we entered
Combo1.SetFocus
End If
End Sub

5.Creating a User defined chart using Picture box control

Creating a userdefined chart in VB6 will be very simpe and easy.

1. Design a form Picture Box and Labels,Text Boxes,and a command Buttons


and a Timer Control as shown bellow.Give TextBox name as TextA, TextB,
TextC, TextD respectively.

2. Set Timer interval tpo 1


3. Add following code to the Command Button’s click event.

Private Sub Command3_Click()


Picture1.Cls

Text2.Text = 5000 - Val(TextA)

Text3.Text = 5000 - Val(TextB)


Text4.Text = 5000 - Val(TextC)

Text5.Text = 5000 - Val(TextD)

Text6.Text = 5000 - Val(TextE)

Timer1.Enabled = True

End Sub
4. Now we need some basic calculations and need to draw lnes (as Chart Bars)

Private Sub Timer1_Timer()

We have to use some loop (what ever it is) to draw chart bars representing A B C
D. After this task we also have to stop the Timer.

For i = 1 To 1500

Picture1.Line (0 + i, Text2.Text)-(0 + i, Picture1.Height), vbRed

Picture1.Line (1500 + i, Text3.Text)-(1500 + i, Picture1.Height), vbGreen


Picture1.Line (3000 + i, Text4.Text)-(3000 + i, Picture1.Height), vbBlue

Picture1.Line (4500 + i, Text5.Text)-(4500 + i, Picture1.Height), vbYellow

Picture1.Line (6000 + i, Text6.Text)-(6000 + i, Picture1.Height), vbMagenta

Next i

Timer1.Enabled = False

End Sub

Advance Visual Basic Programming

1.Create Color Picker/Shading Effect to a picture

This tutorial of vb6 explain how a programmer can create both a picture color
picker and color shader.
In Visual Basic ,a development environment, a coder can create picture color
picker, in which user can pick the color of the picture and apply it to another .This
program use some of the built in functions.

I think this is a good source for both students and teachers as well.

To do the work we have to SetPixel and GetPixel built in Functions


Add these declaration as follows to the General section of the Code Module
Private Declare Function GetPixel Lib "gdi32" (ByVal hdc As Long, ByVal X As
Long, ByVal Y As Long) As Long

Private Declare Function SetPixel Lib "gdi32" (ByVal hdc As Long, ByVal X As
Long, ByVal Y As Long, ByVal crColor As Long) As Long

Secondly we have to create the Shadepicture Function , to this Please Add


these code to the Module
ShadePicture

Public Sub ShadePicture(PicSource As PictureBox, PicTarget As PictureBox,


WithColor As Long, Thickness As Integer)

On Error Resume Next

Dim sRate, Col As Long

Dim X, Y As Single

Dim XMax, YMax As Single

Dim cBlue, cGreen, cRed As Double 'Determines the pixel color

Dim sBlue, sGreen, sRed As Double 'Determines the SHADING color

'Getting the RGB values of selected color

sBlue = Fix((WithColor / 256) / 256)

sGreen = Fix((WithColor - ((sBlue * 256) * 256)) / 256)

sRed = Fix(WithColor - ((sBlue * 256) * 256) - (sGreen * 256))

'Calculate screen height & width of the image


XMax = PicSource.Width / Screen.TwipsPerPixelX - 1

YMax = PicSource.Height / Screen.TwipsPerPixelY - 1

'Initialising Shading

PicTarget.Cls

sRate = Thickness / 10

'Process all pixels and alter them accordingly

For X = 0 To XMax

For Y = 0 To YMax

Col = GetPixel(PicSource.hdc, X, Y)

If Not Col = 0 Then 'Because black colors are usually the borders of an

image and never change border color.It will affect the clarity.

'Getting the RGB values of current pixel


cBlue = Fix((Col / 256) / 256)

cGreen = Fix((Col - ((cBlue * 256) * 256)) / 256)

cRed = Fix(Col - ((cBlue * 256) * 256) - (cGreen * 256))

'Resetting the RGB values of current pixel with the sRate of shading

cRed = cRed + (sRed - cRed) * sRate

cGreen = cGreen + (sGreen - cGreen) * sRate

cBlue = cBlue + (sBlue - cBlue) * sRate

If Not Col = 12632256 Then SetPixel PicTarget.hdc, X, Y, RGB(cRed,


cGreen, cBlue) 'Skipping transparent col and setting the pixel

Else

SetPixel PicTarget.hdc, X, Y, Col

End If

Next Y

PicTarget.Refresh

Next X

End Sub

Now You are ready to Test Your First Shading Program ,By using this You can
Give any color you like to the pictures you using in a VB Project

In order to test the Program you need a Form which contain Three Picture
box control[Original, Processed,ColorPallet as Picture 1] , a scroll bar, and
a picture of color pallet and another as a test picture.
Then Add these Codes

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


Single, Y As Single)

MsgBox Original.Point(X, Y)

End Sub

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


Single, Y As Single)

ShadePicture Original, Processed, Picture1.Point(X, Y), scrRate.Value

End Sub

Private Sub scrRate_Change()

lbThick = scrRate.Value

End Sub

Private Sub Form_Unload(Cancel As Integer)

Clipboard.SetText ("http://tech-guroo.blogspot.com")

If MsgBox("Is it Satisfactory?", vbQuestion + vbYesNo, "?") = vbYes Then

MsgBox "Please Rate my code,The site address is already copied to your


clipboard", vbInformation, "ThankYou"

Else
MsgBox "Please give FeedBack,The site address is already copied to your
clipboard", vbInformation, "Please Give FeedBack"

End If

End Sub

Now You are ready to test your project


You will get the followign result as you move through colors
2. USING THE SHELL32.DLL in VB6

Shell32 is one of the many DLL files that have lots windows in built function which can
be used in ur Visual Basic program. Before we make use of these function you have to
Refer the DLL by adding reference file[Brouse the shell32.dll file]. Secondly you need to
create a instance of shell object which is a container of following functions.

MinimizeAll
EjectPC
ShutdownWindows
SetTime
CascadeWindows

Explore
TrayProperties
FindFiles
TileHorizontally
TileVertically
Help

Add the following vb code to button click event

Private Sub Command1_Click()

Dim shll32 As New Shell

shll32.MinimizeAll

End Sub

Private Sub Command10_Click()

Dim shll32 As New Shell


shll32.EjectPC

End Sub

Private Sub Command11_Click()

Dim shll32 As New Shell


If MsgBox("Shut Down your PC?", vbExclamation + vbYesNo, "SHELL32") = vbYes
Then

shll32.ShutdownWindows

End If

End Sub

Private Sub Command12_Click()

Dim shll32 As New Shell

shll32.SetTime

End Sub

Private Sub Command13_Click()

Dim shll32 As New Shell

shll32.CascadeWindows

End Sub

Private Sub Command2_Click()

Dim shll32 As New Shell

shll32.Explore (Text1.Text)

End Sub

Private Sub Command3_Click()

Dim shll32 As New Shell

shll32.TrayProperties

End Sub

Private Sub Command4_Click()


Dim shll32 As New Shell

shll32.FileRun

End Sub

Private Sub Command5_Click()

Dim shll32 As New Shell

shll32.FindComputer

End Sub

Private Sub Command6_Click()

Dim shll32 As New Shell

shll32.FindFiles

End Sub

Private Sub Command7_Click()

Dim shll32 As New Shell

shll32.Help

End Sub

Private Sub Command8_Click()

Dim shll32 As New Shell

shll32.TileHorizontally

End Sub
Private Sub Command9_Click()

Dim shll32 As New Shell

shll32.TileVertically

End Sub

You might also like