You are on page 1of 52

VISUAL BASIC NOTES

Visual basic is an ideal programming language for developing sophisticated professional applications
for Microsoft windows .It makes use of graphical user interface for creating robust and powerful
applications. Coding in GUI environment is easy and quicker as compare to traditional, linear
programming languages. Visual Basic was developed from BASIC programming language. It required at
least Microsoft windows 95/NT 3.51, 486 processor and minimum of 16 M.B. of RAM and also 250 MB of
hard disk to install complete enterprise edition. Starting Visual Basic 6.0

Visual Basic is initiated by using the Program option -> Microsoft Visual Studio
and Microsoft Visual Basic 6.0 from it. Then it opens into a screen as shown
below (fig 1.1) Fig .1.1

The integrated Development Environment

One of the most significant changes in visual basic 6.0 is the

integrated Development Environment

(IDE).IDE is the term commonly used in the programming world to describe the interface and
environment that weuse to create our applications. It is called integrated because we
can access virtually all of the developmenttools that we need from one screen called an

interface.

The visual basic IDE is made up of a number of components

•Menu Bar

•Tool Bar

•Project Explorer

•Properties Window

•Form layout Window

•Toolbox

•Form Designer

•Object Browser
Menu Bar

1
Trusted by over 1 million members

Try Scribd FREE for 30 days to access over 125 million titles without ads or interruptions!

Start Free Trial

Cancel Anytime.

N o t e s F o r V i s u a l B a
s i c 6 . 0 2

Sunil S. Trivedi

This is bar display the commands that are required to build an application. The main menu
items have submenu items that can be chosen when needed.
Tool Bar

The toolbar in the menu bar provide quick access to the commonly used commands.

Toolbox

The toolbox contains a set of controls that are used to place on form at design time
thereby creating the user interface area. Additional controls can be included in the toolbox by using
the Components menu item of theProject menu. A toolbox is represented in fig 1.2Fig 1.2

The pointer provides a way to move and resize the control and forms.

Label display a text that the user cannot modify or interact with.

Frame control serves as a visual and functional container for control.

Checkbox display a True/False or yes/no option.

Textbox is a control used to display message and enter text.

The Listbox display a list of items from which a user can select one.

ComboBox contains a textbox and Listbox. This allows the user to select an item from DropdownListbox,
or to type in a selection in the textbox.

HScrollBar and VScrollBar controls allow the user to select a value within the specified range of value.

Timer control executes the timer events at specified intervals of time.

Dirlistbox allows the user to select the directories and paths, which are displayed

Shape control use to draw shape on form.

Image control is used to display icons, bitmaps, metafiles


etc2Pointer LabelFrameCheckboxComboboxHScrollBar Timer DirListBoxShapeImageOLEVScrollBar Drive
ListBoxFileListBoxLineDataPictureTextboxCommandButtonOptionButtonListbox
N o t e s F o r V i s u a l B a
s i c 6 . 0 3

Sunil S. Trivedi

OLE control is used to link or embed an object, display and manipulate data from other windows based
applications.

Picturebox displays icons/bmp/jpg and metafiles. It displays text or acts as a visual container for other
controls.

CommandButton control which is a part of an option group allows the user to select only one
optioneven if it display multiple choices.

The FileListBox display a set of files from which user can select the desired one.

The DriveListBox display the valid disk drives and allows the user to select one of them.

Line control to draw a line on form.

Data control enables the user to connect to an existing database and display information from it.

Project Explorer

Docked on the right side of the screen, just under the toolbar, is the project
Explorer window. It dis play objects of your project like forms, c l a s s e s a n d
m o d u l e s . A l l t h e o b j e c t t h a t m a k e u p t h e a p p l i c a t i o n a r e packed in a
project.Fig 1.3 (project explorer )

Properties Window

The properties window is docked under the project explorer window. T h e p r o p e r t i e s


w i n d o w s e x p o s e s t h e v a r i o u s c h a r a c t e r i s t i c s o f s e l e c t e d objects.Fig 1.4 ( Properties
window )

Form Layout

The form layout window use to place the form starting position after you runs it.Fig 1.5 (Form
layout window)

Variables, Data Types and Modules

Variable are used for storing values temporarily. Declaring a variable tells Visual basic to
reservespace in memory. It is not must that a variable should be declared before using it.A defined
naming strategy has to be followed while naming a variable.1.A variable name must begin with
alphabet letter and should not exceed 255 characters.3
N o t e s F o r V i s u a l B a
s i c 6 . 0 4

Sunil S. Trivedi

2.It must be unique within the same scope.3.It should not contain any special
character like %,&, #, @ or $

Syntax

Dim variable [as type]For e.gDim str as stringDim I as integer

Scope of variables

A variable is scoped to a procedure-level(local) or module-level depending on how it


is declared. Avariable is declared in general declaration section of a Form, and hence is
available to all the procedures.Local variable are recognized only in the procedure
in which they declared. They can be declaring with dim and static keyword.

Local Variable:

Local variable is one that is declared inside a procedure. This variable


i s o n l y available to the code inside the procedure and can be declared using dim statement as given
belowDim I as integer

Static Variables

Static variables are not reinitialized each time visual basic invokes a procedure and thus
retains or preserves value even when a procedure ends.e.g.Static in as integer

Module Level Variables

Module level variables are available to all the procedure in the module. They
a r e d e c l a r e d u s i n g Public or private keyword.e.g. public nk as integer private st as stringdeclaring
a variable with public keyword makes it available throughout the application even for the
other modules. A variable can have same name with different scope.

Data Type:

By default Visual Basic variables are of variant data types. The variant data type can store
numeric,date/time or string data. When a variable is declared, a data is supplied for it that determines
the kind of datathey can store.A list of visual basic data types are given below

T y p e N a m e V a l u e s R a n g
e

B y t e 0 t
o 2 5 5 Boolean True or FalseI n
t e g e r -
3 2 , 7 6 8 t o 3 2 , 7 6 7 L
o n g -
2 , 1 4 7 , 4 8 3 , 6 4 8 t o 2 , 1 4 7
, 4 8 3 , 6 4 7 S i n g l e -
3 . 4 0 2 8 2 3 * 1 0

to -1.401298 * 10

45

for negative values.1.401298 * 10

-45

to 3.402823 * 10

38

for positive values.D o u b l e -


1 . 7 9 * 1 0

308

to -4.94 * 10

-324

for negative values4.94 * 10

-324

to 1.79 * 10

308

for positive
valuesD a t e J a n u a r y 1 , 1 0 0 t
o D e c e m b e r 3 1 , 9 9 9 9 4
N o t e s F o r V i s u a l B a
s i c 6 . 0 5

Sunil S. Trivedi

S t r i n g 0 t o a p p r o x i m a t e l y 2
b i l l i o n c h a r a c t e r s C u r r e n c y -
9 2 2 , 3 3 7 , 2 0 3 , 6 8 5 , 4 7 7 . 5 8 0 8 t o 9 2 2 , 3 3 7 , 2 0 3
, 6 8 5 , 4 7 7 . 5 8 0 7

Data Type Conversion


Visual Basic functions either to convert a string into an integer or vice versa and many
more conversionfunctions. A complete listing of all the conversion functions offered by visual basic is
elucidated below.

C o n v e r s i o n T o F u n c t i o n

B o o l e a n C b o o l B
y t e C b y t e C
u r r e n c y C c u r D a
t e C d a t e D e c
i m a l s C d e c D o u b l
e C d b l I n t e g e r
C i n t L o n g C
l n g S i n g l e C n
= s n g S t r i n g C
s t r V a r i a n t C
v a r E r r o r C V
E r r

Note:

A conversion function should always be placed at the right hand side of the calculation statement.

Procedure:

Visual basic programs can be broken into smaller logical components called procedures.
Proceduresare useful for condensing repeated operations such as the frequently used
calculations, text and controlsmanipulation etc. The benefits of using procedures in programming
are:

It is easier to debug a program with procedures, which breaks a program into discrete logical limits.


Procedures used in one program can act as building block for oth
e r p r o g r a m s w i t h s l i g h t modification.A procedure can be sub, function or property
procedure

Sub Procedure

A sub procedure can be placed in standard, class and form modules. Each time
t h e p r o c e d u r e i s called, the statement between Sub and End Sub are executed.

Syntax[private | public ] [ static] Sub Procedure_Name [ (arg_list)][Statements]End Sub

Argument list is separated by commas. Each argument acts like a variable in the procedure. There
aretwo type of sub procedures namely general procedures and event procedures.

Event Procedures

An event procedure is procedure block that contains the control’ s actual name, an
underscore ( _ ),and the event name

Syntax

5
N o t e s F o r V i s u a l B a
s i c 6 . 0 6

Sunil S. Trivedi

Private sub Form1_Load( )Statement blockEnd sub

This is event for form1. Execute when load form.

General Procedures

A general procedure is declare when several event procedure perform the same action. It
is good programming practice to write common statements in separate procedure and
then call them in the event procedure

Function Procedures

Function are like sub procedures, except they return a value to calling procedure. They are
especiallyuseful for taking one or more pieces of data, called arguments and performing
some tasks with them. Thenfunction return value that indicate result of the task.e.g.The following
function procedure calculates area of circle of given radius.

Function Area(a as double) as doubleArea = 3.14 * a^2End Function

Control Flow Statements

Control statements are used to control the flow of program’s execution. Visual
B a s i c s u p p o r t s control structures such as If -- --- -- Then, If -- --- -- Then -- -- -- Else-- End
If. Select----Case and Loopstructures, such as Do While-------Loop, Do-----Loop while and For…..Next
method.

If….Then….Else statement

The If… then block is used for conditional execution of one or more statements. Syntax:

If Condition ThenStatementsEnd If

The statement is execute only if the given condition is true. The condition is usually a comparison, but it
can be any expression that evaluates a numeric value

If….Then …. Else Statement

To execute one block of code if condition is false.Syntax:

If Condition ThenStatementsElseStatementsEnd If

Select ……..Case Statement

Select…Case structure is an alternative to If …Then ….Else If for selectively execute a single block of
statement from among multiple blocks.

Syntax

6
Trusted by over 1 million members

Try Scribd FREE for 30 days to access over 125 million titles without ads or interruptions!

Start Free Trial

Cancel Anytime.

N o t e s F o r V i s u a l B a
s i c 6 . 0 7

Sunil S. Trivedi

Select Case IndexCase 0StatementsCase 1StatementsCase nStatementsEnd Select

Select …. Case statement evaluates an expression once at the top of the block where as if…then
elsestructure evaluates different expressions for each Else If statement.

Do While…..Loop statements

The Do While …. Loop is used to execute statements until a c ertain condition is met.
Following dowhile .. loop counts from 1 to 100

Count=1Do while count < 100Count = count + 1Loop

Do…Loop While Statement

The do…..loop While Statement first execute the statements and then test the condition
after eachexecution. The following program block is same to first one(like Do While loop)Count = 200

Do Text1.text = str(count)Count=count + 1Loop While count < 300

The program execute the statements between do and loop while structure in any case.
Then it determinesweather the count is less than 300. If so, the program again execute block until it
gets false.

Do….Loop Until statement


The do….loop until structure execute the statements until the condition is satisfied. It is
an infiniteloop if the test fails and to get released fr om this loop we can use CTRL + BREAK
combination or EndFrom Run menu.The following code entered in the Form Load() procedure
illustrates the structure.

Private Sub Form_load()DoX$ = INputBox$(“Password ?”)Loop until X$ = “Sunil”End Sub

The For….Next Loop statement

The for…Next Loop is another way to make loops in visual basicSyntax

For Var_name = Start_val to End_val [ Step Number]

N o t e s F o r V i s u a l B a
s i c 6 . 0 8

Sunil S. Trivedi

StatementsNext [Var_name]For I = 1 to 100 step 1 Text1.text = str(I)Next I

Exit For and Exit Do Statement

A For…Next Loop Can be terminated by an Exit For Statement. Consider the following statement block

For I = 1 to 100 Text1.text = str(i)If I= 50 thenExit ForEnd if Next

In this example loop is for 1 to 100 but we stop or exit from loop by using exit for
statement in it. Same wecan exit from do loopI = 1Do while I < 100Text1.text = str (I)I = I+ 2If I > 50
thenExit DoEnd If Loop

With ….. End With Statement


When properties are set for objects or methods are called, a lot of coding is included that
acts on thesame object. It is easier to read the body by implementing with With… End With
statement.For e.g suppose we want to set properties for Form then

With form1.backcolor = qbcolor(2).enabled = True.MaxButton = false.Font = “Times”End with

In the above coding, the object form get all its properties which we set in with block.

Modules

Code in visual basic is stored in the form of modules. The three kinds of modules are Form
module,Standard module, and class modules. A simple application may contain a single form and the
code resides inthat Form module itself. As the application grows, additional Forms are
added and there may be a commonc o d e b e t o e x e c u t e d i n s e v e r a l F o r m s . T o a v o i d
t h e d u p l i c a t i o n o f c o d e , a s e p a r a t e m o d u l e c o n t a i n i n g a procedure is created that
implements the common code. This is a standard module.Class module is a foundation of the object
oriented programming in visual basic. New objects can becreated by writing code in class modules. Each
module can contain variable declaration or procedures.

Array in Visual Basic

N o t e s F o r V i s u a l B a
s i c 6 . 0 9

Sunil S. Trivedi

A sequence of variables by the same name can be referred using array. The individual elements of
anarray identified using an index. Arrays have upper and lower bounds and elements have
to lie within those bounds. Each index number in an array is allocated individual memory
space. We can declare array of typevariant, user defined types and object variables.

There are two types of array


Fixed size array: The size of array always remains the same

Dynamic array: The size of can be changed

Fixed Size Array

Fixed array can be declared by giving a name with the upper limit in the parentheses. The long data
type.e.gdim lengths(10) as Integer In the above illustration, lengths is a name of the array and
the number 10 include in the parentheses is the upper limit of the array. This create array having
10 elements with index number from 0 to 9.Dim length(1 to 10) as Integer having lower limit 1 to upper
index number 10.Dim marks(50,50) it create two dimensional array.Dim marks(1 to 10,1 to 10) it create
two dimensional array with lower and upper limits.

Dynamic array

There will be a situation when the user may not know the exact size of the array at design
time. Under suchsituation, a dynamic array can be initially declared and can add elements
when needed instead of declaringthe size of the array at design time.Dim newarray( )The actual
elements can be allocate using ReDim statementReDim newarray( n )Each time on the executing the
ReDim statement, the current data of array is lost and the default value is set.But if we want to change
the size of array without lost any previous elements then use keyword PreserveReDim Preserve
newarray(20)

User-Define Data Type

Variable of different data types when combined as a single variable to hold several related
information iscalled user-define data type.A type statement is used to create new type. User-
define type can only be private in form while in standardmodules can be public or
private.e.g.Private type student Name as stringAge as integer Per as doubleEnd typee.g.Creating
variablesDim s1 as studente.g.Or creating array9
N o t e s F o r V i s u a l B a s
i c 6 . 0 1 0

Sunil S. Trivedi

Dim s(10) as student

Accessing members of user-define type

Variable name.member namee.g.text1.text = s1.name accessing name of student s1

Visual Basic Built-in Functions

Many built-in functions are offered by Visual Basic that fall under various categories.

Date function

Format functions

String functions

Date Functions

Now Return current system date and time.Y e a r ( ) R e t u r n y e a r n u m b e r


f r o m g i v e n d a t e . M o n t h ( ) R e t u r n m o n t h n u m b e r f r
o m g i v e n d a t e . D a y ( ) R e t u r n d a y o f g i v e
n d a t e . WeekDay()Return week day number from
given date.H o u r ( ) R e t u r n h o u r n u m b e r f o r m g i v e n
t i m e . M i n u t e ( ) R e t u r n m i n u t e f r o m g i v e n t i m e Second() r
eturn second from given time.

DateAdd()
Return a date to which specific interval has been added.Syntax: DateAdd(interval,number,Date)Where
interval is “M” ,”D” or “Y” Number to add in dateDate in which you want to
add.e.g.DateAdd(“m”,3,”02/14/2002”) it return 06/02/2002 (add 3 month in date)

DateDiff()

Returns a

Variant

Long

) specifying the number of time intervals between two specified dates.

SyntaxDateDiff(

interval, date1, date2

, firstdayofweek

firstweekofyear

]]

The

DateDiff

function syntax has these named arguments:


P a r t D e s c
r i p t i o n

interval

Required. String expression that is the interval of time you use to calculatethe difference between

date1

and

date2

date1

date2

Required;

Variant

Date

). Two dates you want to use in the calculation.

firstdayofweek

Optional. A constant that specifies the first day of the week. If not specified,Sunday is assumed.10
N o t e s F o r V i s u a l B a s
i c 6 . 0 1 1

Sunil S. Trivedi

firstweekofyear

Optional. A constant that specifies the first week of the year. If notspecified, the first week is assumed to
be the week in which January 1occurs.

Dim TheDate As Date ' Declare variables.Dim MsgTheDate = InputBox("Enter a date")Msg = "Days from
today: " &

DateDiff(
"d"

Now

TheDate

MsgBox Msg

DatePart()Returns an integer containing the specified part of the


given dateDateValue()Convert a string into date format.

String Functions

StrComp()Compare two stringsL c a s e ( ) C o n v e r t


t h e g i v e n s t r i n g i n t o l o w e r c a s e
. U c a s e ( ) C o n v e r t t h e g i v e n s t r i n g i n t o U p p e r
c a s e . L e n ( ) R e t u r n a l e n g t h o f g i v e n s t r
i n g Format()Convert a given string into given
f o r m a t . L s e t ( ) , R s e t ( ) J u s t i f y a s t r i n g Instr()Return a variable(long) specifying the
position of the first occurrence of the string within another.Letf()Return specified number
of character from left side of given stringRigth()Return specified number of character from Right
side of given stringTrim()Return a given string by removing all it’s blank space from left and
right side.Mid()Return a specified number of character from mid of given string.Ltrim()Trim
all blanks of left hand
side.R t r i m ( ) T r i m a l l b l a n k s o f R i g h t h a n d s i d e .

Working with Forms

In visual basic, the form is the container for all the controls that makes up the user interface. A form may
fillentire screen or have other forms within it. It may be a custom dialog box. When a
Visual basic applicationis executing, each window it displays on the Desktop is Form.
Setting Form Properties

Border Style

None No border is shown.F i x e d s i n g l e A s i n g l e -


p i x e l w i d t h b o r d e r i s s h o w n S i z a b l e T h
i s i s d e f a u l t s e t t i n g . F i x e d
D o u b l e A d o u b l e - p i x e l w i d t h i s s h o w n a r o u n d t h e
f o r m . Fixed ToolWindowthis type of border is use for
t o o l b a r s . Sizable ToolwindowSame as fixed toolwindow, but border are resizable.

Caption

The title for the window is store in the caption property.

Control Box

This is determine weather the control box, available by clicking the upper left corner /icon of a
window.IconThis property specify the icon for the window in the upper-left corner of the window11

Trusted by over 1 million members

Try Scribd FREE for 30 days to access over 125 million titles without ads or interruptions!

Start Free Trial


Cancel Anytime.

N o t e s F o r V i s u a l B a s
i c 6 . 0 1 2

Sunil S. Trivedi

MousePointer

This property sets the value that indicate the type of mouse pointer displayed.

MaxButton/MinButton

Set max or min button of window which are present on title bar.

Moveable

By setting it false it is possible to prevent the user from moving window.

MDIChild

This property specifies if this window must be shown within a multiple document interface (MDI)
window.

StartUpPosition

Set the starting position of window.

Displaying Forms

Show Method

The show method is used to display the form object. For e.g. to display the form
frmcalculator, thefollowing code is written.

Frmcalculator.show

Using Load Statement


The load statement is used to load a form or control into memory but does not display it.
To load theform frmcalculator, the following code should be enter.

Hiding and Unloading FormsUsing the Hide Method

The hide method hides a form. For e.g., the following code hides the form object frmcalculator

Frmcalculator.Hide

Using the Unload Statement

The unload statement removes the form from the display and releases the memory. The
followingcode should be entered to unload frmcalculator from memory.

Unload frmcalculator

Setting Run time and design time properties

Many properties can be set at either design time or runtime. At design time, the controls are added toa
project, their properties set and relevant code is written.To set properties at design time following steps
are followed.1 . S e l e c t the control or object whose properties you want to
set.2 . A c t i v a t e the property w i n d o w 3.Scroll to the property you want to
set4 . E n t e r a n e w s e t t i n g . At run time properties can change by program’s code. This
is done by

Object.propertyname = value

e.g

Private Sub Form_Load()

12

N o t e s F o r V i s u a l B a s
i c 6 . 0 1 3
Sunil S. Trivedi

Form1.backcolor = QBcolor(3)Form1.Caption = “Sample Application”F o r m 1 . W i n d o w S t a t u s =


V B N o r m a l Form1.Width = 5000Form1.Height = 5000End Sub

Creating and Using Controls

A control is an object that can be drawn on a Form object to enable or enhance


u s e r i n t e r a c t i o n w i t h a n application. Controls

Classification of controls

Visual Basic Controls are broadly classified as standard controls, Active X controls
and insert-able objects.Standard controls such as CommandButton, Label and frame
controls are contained inside .EXE file and arealways include in the ToolBox which cannot be
removed. ActiveX controls exist as separate files with either .VBX or .OCX extension. They include
specialized controls, few from them given below

MSChart control

The Communication control

The Animation control

TreeView control

The Picture clip control

SysInfo control
Text Box Control

A TextBox control, some times called an edit field or edit control, display information entered time at
designtime, entered by the user at run time or assign any value at run time.

Some Properties of a Text BoxName

This is a name used in program to identify the control

MaxLength

Set maximum no of characters that can be entered in control.

MultiLine

weather a control can accept multiple lines or not.

PasswordChar

It replace the text of control with given character with.

Text

to assign text to control at design time.

Command Button

A command Button control to begin, interrupt, or end a process. When chosen, a


Command Button appears pushed in and so is sometimes called push button.

Properties of a command button control

To display text on a command button control, set its caption property.An event can be activated by
clicking a command buttonA button’s background color can be set by setting Backcolor property.Text
color of a command button can be set using forecolor property.Font can be change using font
property.Enabled or disable buttonTooltip text can be set using Tooltip property.A button click event is
handled whenever a command button is clicked. To add a click event handler,double click on button at
design time, which adds a subroutine like the one given below.

Private sub Command1_Click()...... . .


13

N o t e s F o r V i s u a l B a s
i c 6 . 0 1 4

Sunil S. Trivedi

End Sub

Using option button control

Option button a set of choices from which a user can select only one button by

Clicking at run time.

Assigning the value property to True in code like Option1.Value = True

Using the shortcut keys specified in the caption of a labelTo disable Option button at run time its
Enabled property set to False.

Using Listbox and ComboBox Controls

ListBox and ComboBox controls present a set of choices that are displayed vertically in
a single column. If t h e n u m b e r o f i t e m s e x c e e d t h e v a l u e t h a t c a n b e d i s p l a y ,
s c r o l l b a r s w i l l a u t o m a t i c a l l y a p p e a r o n t h e control. These scroll bars can be scrolled up and
down or left to right through the list.

Adding items to a list

It is possible to populate the list at design or at run time.


Design Time:

To add items to a list at design time, click list in the property box and then add the
items.Press CTRL + ENTER after adding each item.

Run Time:

The AddItem method is used to add items to a list at run time. The AddItem method uses
thefollowing syntax:Object

AddItem item, IndexThe item argument is string that represents the text to add to the list.The index
argument is an integer that indicates where in the list to add the new item.

Removing Items from a List

The RemoveItem method is used to remove an item from a list. The syntax for this is given
below.Object.RemoveItem.index

Selecting an Item from a list

To access the items in a listbox we use the ListIndex and List properties. The list index property setsthe
index number of the currently selected item. The first item in the list having index number
0. ListIndexreturn -1 if no item is selected. The list count return total number of items in listbox.

Sorting the List

To sort the list set sorted property to True.

Using ComboBox

A Combo Box combines the features of Textbox. This control enables the user to select
either bytyping text into combo box or by selecting an item from list.There are three types of Combo
Box styles that are given below.Dropdown Combo (style 0)Simple Combo (style 1)Dropdown list (style 2)

Using ScrollBar Control

The Scrollbar is a commonly used control, which enables the user to select a value
by positioning ita t t h e d e s i r e d l o c a t i o n . I t r e p r e s e n t s a s e t o f v a l u e s . T h e m i n
m a x p r o p e r t y r e p r e s e n t s t h e m i n i m u m a n d maximum value. The value property represents
its current value.14

N o t e s F o r V i s u a l B a s
i c 6 . 0 1 5

Sunil S. Trivedi

Managing Menus

Creating and managing menu at Design TimeV i s u a l Basic applications can be


e n h a n c e d b y a d d i n g m e n u s t o i t . I t o f f e r s a c o n v e n i e n t a n d consistent way to
group commands and easy way for users to access them.The menu bar appears appear below the
title bar and it may contain one or more menu titles. When ame nu title is clicked it
displays a set of menu items under that title. Each menu item corresponds to
a menucontrol that is defined in a menu editor and performs a specific action.

Using the Menu Editor

A menu editor can be used to add new commands to


thee x i s t i n g b a r s . A m e n u e d i t o r c a n b e a d d e d o n l y a f t e r o p e n i n g a
project. To display a menu editor command is c h o s e n f r o m t h e T o o l s m e n u o r
m e n u e d i t o r b u t t o n i s clicked in the tool bar.Writing Code form menu ControlE a c h m e n u
c o n t r o l h a s c l i c k e v e n t , w h i c h i s e x e c u t e when the menu item is selected or clicked.
The followingcode is entered in the code window for green color option of menu.

Private sub grn_Click()Form1.backcolor= QBcolor(2)Grn.Enabled = FalseBlue.Enabled = TrueRed.Enabled


= TrueEnd sub

When the green color is selected by clicking on it, form backcolor will be
c h a n g e i n t o g r e e n c o l o r a n d t h a t g r e e n option form menu is make disable and to other’s
enable.
Adding a Separator Bar and Shortcut key.

Separator bar is a line that separates the menu items, which is mainly useful for obtaining
clarity. Toadd it in menu, Right click on the form select menu editor Place the pointer where you want
to insert separator In the caption TextBox ‘-‘ is typed and give any name15Title Bar Menu Bar Separator
bar
N o t e s F o r V i s u a l B a s
i c 6 . 0 1 6
Sunil S. Trivedi

Using Access and Shortcut keys

Access keys allow the user to open a menu by pressing the Alt key with a letter key. To open the Edit
menuin all Windows applications, for e.g. you can press Alt-E. .A c c e s s k e y i s d e s i g n e d b y t h e
p r o g r a m m e r a n d t h e y a r e m a r k e d w i t h a n u n d e r l i n e c h a r a c t e r . T o a s s i g n Access
key to menu item, add & sign before letter. e.g. “&File”.

Shortcut Keys

Shortcut keys are similar to access key has a special meaning in menu design, but inside a
opening menu,they run a command when pressed. To assign a shortcut key to a menu command,
dropdown the shortcut listin the menu editor and select a keystroke.

Pop-Up Menus

A pop-up menu is a floating menu that is displayed over a form independent of the menu bar. Pop-
upmenus are also called context menus. Because the items displayed on the pop-up menu depend on
where the pointer is located when the right mouse button is clicked.Any menu can be displayed as a
pop-up menu at run time provided it has one menu item.The following code displays the colors
menu when the user clicks right mouse button over the form at run time.

Private Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)If Button = 2
ThenPopupMenu ccEnd If End Sub

Making menu control invisible

It run time if user wants to enable and disable to menu items, it is possible by setting the
Enabled property to True or False. When a menu item is disabled, it is dimmed and cannot
be selected. But it is stillvisible and the menu items seen.Mnu_green.Enable = FalseBut if you want
to hide menu item from display set visible property false for it.Mnu_green.Visbile = False

Using Check Marks

In some programs we may require check marks to be placed in the menu items. To place
a check mark in amenu item, the checked property is set to true. The following example
code entered in the Form_load( ) procedure places a check mark in the menu item
Red.Mnured.checked = True

Menu Control Array:

A menu control array is a set of menu items on a menu that shar e the name and
e v e n t p r o c e d u r e . Each menu control array element is identified by a unique index value,
indicated in the Index property boxon the menu editor. When the member of the menu control
array recognizes an event, visual basic passes theindex property value to the event procedure as
additional argument. The event procedure must include the code that can check the value of
the index property.

Mouse Events

Visual basic applications respond to various mouse events, which are


r e c o g n i z e d b y m o s t o f t h e controls. The main events are MouseDown, MouseUp and
MouseMove. MouseDown occurs when the user 16

Trusted by over 1 million members

Try Scribd FREE for 30 days to access over 125 million titles without ads or interruptions!

Start Free Trial

Cancel Anytime.

N o t e s F o r V i s u a l B a s
i c 6 . 0 1 7

Sunil S. Trivedi
presses any mouse button and MouseUp occurs when the user releases any
m o u s e b u t t o n . M o u s e M o v e occurs whenever the mouse pointer is moved to a new
point on the screen. These events use the arguments button, Shift, X, Y and they contain
information about the Mouse’s condition when the button is clicked.The first argument is an
integer number called button. The value is 1 if left button is clicked and 2 if right button is
clicked.T h e s e c o n d a r g u m e n t i s a n i n t e g e r c a l l e d s h i f t . T h e v a l u e o f t h i s a r g u m e n t
i n d i c a t e s w e a t h e r t h e mouse button was clicked simultaneously with the Shift key or Alt key.T h e
third and fourth arguments X and Y are the coordinates of the mouse location
a t t h e m o u s e button was clickede. g.This is program to draw a line on form with the help of
mouse.First method the starting points, when you press mouse button down to draw line(MouseDown
events)

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As


Single)Form1.CurrentX = XForm1.CurrentY = YEnd Sub

Second method for drawing a line on current points (Mouse/Move events)

Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)If Button = 1


ThenLine (Form1.CurrentX, Form1.CurrentY)-(X, Y)End If End Sub

Dragging and dropping

Dragging is a process of clicking the mouse button in a control and moving the mouse
while holdingdown the mouse button. The action of releasing the mouse button after the
dragging is called dropping. The following drag-and –drop properties, events and method are
supported in Visual Basic.DragMode property enables automatic or manual dragging of a control.
DragIcon property specifies the iconthat is display when the control is dragged.D r a g D r o p e v e n t i s
recognized when a control is dragged onto t he object. DragOver event is
r e c o g n i z e d when a control is dragged over the object.Drag method starts or stops manual
dragging.All the controls except menus, timer, lines and shapes support the above
mentioned properties andmethod. Forms recognize the DragDrop and DragOver events
but they do not support Drag method and the properties DragMode and
DragIcon.T o d e v e l o p a n a p p l i c a t i o n t o e x p l a i n d r a g a n d d r o p events we use a
image, textbox and command button

P r i v a t e S u b C o m m a n d 1 _ D r a g O v e r ( S o u r c e A s C o n t r o l , X A s Single, Y As Single, State As


Integer)Dim inf As Stringinfo = "NOW DRAGGING "info = info + img.Tag

17
N o t e s F o r V i s u a l B a s
i c 6 . 0 1 8

Sunil S. Trivedi

info = info + " OVER THE Exit button"info = info + " STATE" + Str(State)Text1.Text = infoEnd SubPrivate
Sub Form_DragDrop(Source As Control, X As Single, Y As Single)Text1.Text = ""img.Move X, YEnd
SubPrivate Sub Form_DragOver(Source As Control, X As Single, Y As Single, State As Integer)Dim inf As
Stringinfo = "NOW DRAGGING "info = info + img.Taginfo = info + " OVER THE FORM "info = info + "
STATE" + Str(State)Text1.Text = infoEnd Sub

In this program when user drag image icon on form or command button related
m e s s a g e w i l l b e display on the screen, and when release the mouse the image will be place or move
on the current location of mouse pointer.

File Controls

Usually you use the Common Dialog File Open and File Save As to get file names and file
pathsfrom the user, but sometimes that just won’t do. For e.g. you have a program where
you want to let user select files but don’t want to use dialog boxes, In that and similar
cases, you can use the visual basic file controls:

The Drive List Box, Directory List Box and File list Box

Drive List Box:

Use this tool to draw a drive list box in a form, you get currently selected drive in a drive
list by using itsDrive property, and when the user changes the drive in the control, a
Change event is generated. But File controls always work with each other.e.g.18Drive List boxFile
List boxDirectory List box

RichText BoxText Box


N o t e s F o r V i s u a l B a s
i c 6 . 0 1 9

Sunil S. Trivedi

Here in e.g when the user selects a new drive, we pass that new drive on ot a directory list
box, dir1 usingthat drive as the new root directory in Dir1:Sub Drive1_Change()Dir1.Path =
Drive1.DriveEnd Sub

Using The Directory List Box

The directory list box control displays directories as a hierarchical set of


folders. The important property of the list box is

Path

property, which holds the path of the current directory. When the user c h a n g e s t h e
current path, a

Change

e v e n t s i s g e n e r a t e d . F o r e x a m p l e , w h e n t h e u s e r m a k e s a c h a n g e i n directory list
box, dir1, we can pass the new path to file list box, File1Sub Dir1_Change()File.Path = Dir1.PathEnd Sub

Using The File List Box Control

The file list box control lets you display the files in a directory as a list of names.The important
properties of the File list box are

Path

and

FileName

properties. In our e.g. we load files e l e c t f r o m F i l e L i s t b o x t o P i c t u r e B o x a n d t x t


f i l e i n R i c h T e x t B o x . S o w h e n w e c l i c k o n F i l e n a m e following event get execute.
Private Sub File1_Click()On Error Resume NextDim fname As Stringfname = File1.Path + "\" +
File1.FileNameText1.Text = fnameIf LCase(File1.Pattern) = "*.bmp" Or LCase(File1.Pattern) = "*.gif" _ Or
LCase(File1.Pattern) = "*.ico" ThenPicture1.Picture = LoadPicture(fname)ElseIf LCase(File1.Pattern) =
"*.txt" Thenrtb.FileName = fnameEnd If End Sub

Graphics for Application

Visual Basic provides a variety of ways to create and usegraphics in an application, which
adds styles, interest and visualstructure to the interface of an application. Graphic objects
suchas lines, circles and bitmaps can be displayed in visual basic in aquicker and easier
way.19

N o t e s F o r V i s u a l B a s
i c 6 . 0 2 0

Sunil S. Trivedi

The number of times a twip is used by all visual basic movements, sizing and
graphical drawingstatements is limited to one. A twip is a unit that specifies
t h e d i m e n s i o n s a n d l o c a t i o n o f t h e g r a p h i c s objects. There are 1440 twips in one inch.
Thses measurements designate the size when printed.The coordinate system is a two dimensional
grid that defines the location on the form or any other container which is represented
as(X, Y). X represents the location of a point on the X-axis and Y representsa point on the Y-
axisA color is represented by long integer and there are four ways of specifying it at run
time. They arespecified using RGB function, QBColor function, and using one of the intrinsic constants
listed in the ObjectBrowser and by entering a color value directlyRGB(255,0,0) return Red
color RGB(0,255,0) return Green color RGB(0,0,255) return Red color QBcolor function takes a single
number that specifies a Quick Base color number from 0 to 15 and returns along integer that can be
used in visual basic color property.Form1.backcolor = QBColor(4)

Using Graphics Controls

Visual Basic provides three controls to create graphical applicat ions such as image, Line
and shape.These controls are very useful at design time.The main advantage of graphics controls is
that we can create an application with less code.

Line Control

A line control is a straight-line segment that is drawn at design tim e. The position, length,
color andstyle of the line control can be positioned to customize the look of an application

Shape Control

A shape control is a Visual element that contains several predefined shapes. In


o r d e r t o v i e w a specified shape, the control is added to the form by double clicking it.
The default shape will be rectangle.The shape property is selected from the properties
window, which drops down a list of shapes, from which the user can select the desired one.The
FillColor, FillStyle properties of the Shape control can be changed so that desigred color
andstyle can be obtained.

Image Control

An image control is a rectangular portion into which picture files can be loaded. The
picture files include bitmap files, icon files and metafiles.

Adding Pictures:
Line control and shape control are used for drawing geometrics shapes such as lines,
circles, squares and soo n . F o r d r a w i n g m o r e c o m p l e x f i g u r e w e c a n u s e a p i c t u r e
f i l e . A p i c t u r e f i l e c a n b e l o a d e d o n a f o r m , image control or Picture Control.

A picture can be added by the following two ways at design time.

In the properties window of the Form, the Picture property is selected. Visual Basic displays a dialog box
from which a picture file can be selected. Similarly a picture can be loaded in a PictureBox
andImage control.

A picture can be paste on form or into PictureBox or Image control

A picture can be added by the following ways at run time.

LoadPicture function is used to specify the filename and assign the picture to the Picture
property.Picture1.Picture = LoaPicture(“C:\Image\sst.jpg”)20

N o t e s F o r V i s u a l B a s
i c 6 . 0 2 1

Sunil S. Trivedi

Any picture loaded to a form, PictureBox or Image control can be copie


d t o a n o t h e r F o r m , PictureBox or Image control.Set picture1.picture = Image1.Picture


A picture can be copied from ClipBoard objectRemoving PictureA picture can be removed at run time
using LoadPicture function without arguments.Set image1.picture = LoadPicture(“ “)Moving and Sizing
PicturesI f a f o r m , P i c t u r e B o x o r a n I m a g e c o n t r o l i s m o v e d , t h e p i c t u r e a s s o c i a t e d
w i t h i t a l s o m o v e s automatically. The autosize property of a picture box can be set to True in order
to automatically expand andaccommodate a new picture.Using Graphics MethodsEvery graphics
method draws output on a Form, PictueBox or to the printer object. The
followingstatement draw a point on the formForm1.PSet(500,500)The PSet method draw a point at x, y
co-ordinates that is specified by its arguments.Form1.ClsClear all the graphicsPixelColor =
point(30,40)Point method return the color of a particular pixel.Line(x1, y1) – (x2, y2), Color Line method
draw a line from x1,y1 to x2,y2 of given color, x1 ,y1 is a starting point coordinates and x2, y2is ending
points.Visual Basic provides a much simpler way to draw a box.Line(600,600) – (1000,1000),
Qbcolor(4),BB option is used with Line Method to draw a box.A Circle method is used to draw a
variety of circular and elliptical shapes. To draw a circle Visual Basic required the location of
the circle’s center and length of its redius.Circle(1400, 1200), 500

Multiple Document Interface (MDI)

MDI stand for Multiple Document Interface. A Multiple Document Interface is used for
openingm a n y W i n d o w s a t t h e s a m e t i m e . A l l t h e d o c u m e n t w i n d o w s a r e
contained in a parent w indow,
w h i c h p r o v i d e s a w o r k s p a c e i n t h e a p p l i c a t i o n . V i s u a l B a s i c applications can
have only one MDI form, which containsall the child forms. A child form is an ordinary
Form thath a s i t s C h i l d p r o p e r t y s e t T r u e . C h i l d f o r m a r e d i s p l a y within the
internal area of MDI form at run time.

Add new MDI form to Project:

To add new MDI form, select it from project menu or right click on project name in
Explorer window and selectAdd, MDI form.21

You might also like