VB - 2024
VB - 2024
By Jayesh Gori
2
By Jayesh Gori
INTRODUCTION
Visual Basic is a programming language developed by Microsoft that allows you to develop
GUI Graphical User Interface application for windows.
VB is designed to allow the programmer to develop application that runs under Windows
without complexity generally associated with Windows programming.
In VB with very little effort programmer can design a screen that holds standard Windows
element such as command buttons, check boxes, option buttons, and text boxes. Each of this
windows object produce a standard Windows user interface.
VB is based on the old BASIC (Beginner’s all purpose Symbolic Instruction Code) language,
which was totally text and dos based language.
BASIC has been around for more than 35 years in one form. It was developed for beginners.
With BASIC new programmer can work efficiently than older language such as COBOL,
FORTON and Assembler, require more study than BAISC.
BASIC is strictly a text based language. Both its program and output are textual and do not
produce the graphic. Because it was CUI (Character User Interface) based language.
But with the development of new hardware and new Windows OS there was a need of new
language which can work easily with GUI based OS like Windows.
So Microsoft decided to create language that support GUI and finally they created a language
called Microsoft Visual Basic which is totally GUI based.
The first version of VB is VB 4 then after few months the new upgraded version VB 5 came, but
not as great changes as the upgrade from 4 to 5.
And finally the new version of VB came in market which is known as VB 6 that introduce many
new features.
Visual Basic comes in three varieties Visual Basic Enterprise Edition, Visual Basic
Professional Edition, and Visual Basic Learning Edition.
3
By Jayesh Gori
In VB you will work with object which has properties and methods.
Objects:
Objects are the basic run time entities in an object oriented system. They may represent a
person, a, place, a bank account, a table of data or any item that the program has to handle.
Objects take up space in memory and have an associated address.
Properties
Properties tell something about an object such as its name, color, size, location or how it will
behave.
Methods
Predefined actions that can be performed by an object. For example form has hide method that
makes the form invisible.
Event
An action initiated by the user, the OS or by the program itself. For eg.Keystroke, mouse click.
4
By Jayesh Gori
VB IDE (Integrated Development Environment)
Menu Bar
Displays the commands you use to work with VB. Besides the standard File, Edit, View,
Window and Help menus are provided to access functions specific to programming such as
Project, Format, or Debug.
Context Menus
Contain shortcuts to frequently performed applications. To open a context menus right click the
mouse button on the object you are using. The specific list of option available from context
menus depends on the part of environment where you right click the mouse button.
Toolbars
Provide quick access to commonly used commands in the programming environment. You click
a button on the toolbar to carry out the action represented by that button. By default the standard
toolbar is displayed when you start VB.
Toolbox
The toolbox is the probably the first window you’ll become familiar with because it lets you
visually create the user interface for your applications.
Properties window
The properties window lists all the properties of the object that’s currently selected and gives
you the opportunity to modify them.
You can list the properties alphabetical order or group them in categories, and you can find the
short description of the currently selected property near the bottom of the window.
When you select an object, its properties are automatically displayed in the properties window.
5
By Jayesh Gori
The form designer window
You can use the form designer window to design your applications user interface. You can add
controls, graphics and pictures to a form to create a look you want.
Any application can contain multiple forms and you can also open multiple form designers at
the same time.
Immediate window
The immediate window lets you enter a command or expression and see its result using the print
command (which can also be shortened?).
In break mode that is when you have temporarily suspended a running program you can also use
these commands to display the current value of a variable. You can open it by pressing CTRL +
G
6
By Jayesh Gori
The local window
The local window is active only when a program is executing. It lists the value of all the
variables that are local to a module or to a procedure.
If the variable is an object itself (for example, form or control) a plus (+) sign appears to the left
of the variable name, which means that you can expand it and look its properties.
Watch Window
The watch window has dual purpose; it lets you continuously monitor the value of a variable or
an expression in your program, including the global variable, which is outside the capabilities of
the local window and its also gives the ability to stop the execution of the program when a given
expression become true or whether its changes its value.
Data types
VB supports several native data types, including native data types. You can store data in variable of
proper type.
Byte
Integer
Long
Single
Double
Currency
String
Date
Boolean
Object
Variant
7
By Jayesh Gori
Byte
Byte data type can hold an integer numeric value in the range through 0 to 255.
They take only one byte (8 bits) each and therefore it is the smallest data type in vb.
So it is used to hold small value such as person’s age.
Eg Dim age as byte
Integer
An integer data type is used to store the whole number range from -32 768 through 32 767
It occupies 2 bytes (16 bits) space in memory.
Eg Dim no as integer
Long
A long integer is a natural number whose values is between -2 147 483 648 to 2 147 483 642.
This data type is larger then integer and it occupies 4 bytes (32 bits) in memory.
Eg Dim lno as Long
Single
Single variable can hold decimal values in the range from -3.402823E38 to - 1.40 1298E-45 for
negative values and 1.40 1298E-45 to 3.402823E38 positive values.
It occupies 4 bytes (32 bits)
Eg Dim sale as single
Double
Double variable can store floating point value in the range -1.79769313486232E308 through -
4.94065645841247E-324 for negative value and 4.94065645841247E through
1.79769313486232E308 positive values. They take 8 byte in memory.
EgDim area as double
Currency
Currency format can hold decimal values in fixed point format, in range from
-922,337,203,685,477,5808 through 922,337,203,685,477,5807. They differ from floating point
variables, such as single and double , in that they always include four decimal digits.
String
String data type is used to store text only. VB manage two different types of strings; variable
length string and fixed length strings.
Eg. Dim str as String variable length
o Dim Fstr as String*50 fixed length
String *size
8
By Jayesh Gori
Date
Date data type is used to store date and time information. Date variables can store any date
between January 1,100, through December 31, 9999 as well as any time value. They take 8
bytes.
You can define a date constant using the format #mm/dd/yyyy#
EgmyBdate = #01/28/2005#
Boolean
The Boolean data type is used to store ture/fase or 1/0. It occupies 2 bytes in memory.
Object
VB uses object variable to store reference objects. Object variable are stored as 4 bytes address
that refer to the objects within an application or within some other application.
Object variable can be grouped in two categories. Generic object and specific object
Variant
A variant is the default data type for VB. In other words if you use variable without first
declaring , VB creates Variant variable Eg Dim no .
A variant variable is capable of storing all system defined types of data. In short variant type
can store any type like int, stirng,
float.
9
By Jayesh Gori
Single Single precision floating point number with Sng sngMark
six digits of accuracy.
String Alphanumeric data, letters, digits and other Str strName
characters.
Variant Converts from one type to another as Vnt vntChange
needed.
Variable
In vb you use a variable to temporarily store values during execution of an application.
Variable have a name , the word you use to refer to the value the variable contains, and a data
type, which determines the kind of data the variable can store.
Variable declaration
There are 2 ways to declare variable.
Implicit
Explicit
If variables are not implicit or explicit typed, they are assigned the variable as variant type by default.
Implicit
Variables that are not (explicitly) declared with Dim statements are said to be implicitly
declared. Such variables, which have a data type called Variant, can hold strings, numbers, and
several other kinds of information
In implicit variable you don’t have to declare variable before using it.
Explicit
There are many advantages to explicitly typing variables. Primarily we insure all computations
are done properly, mistyped variables are easily spotted and vb will insure consistency in upper
and lower case letters used in variable names.
For eg : Dim no as integer
11
By Jayesh Gori
Controls
Form Control
The form is the most important visible object,without it no control can be displayed. It is a
window that can be designed and modified to fit user applications. In the standard project the
form Designer creates and modifies visual forms .When user starts visual Basic program a form
is automatically displayed in Designer window. The designer can add any number of forms to
the project of his application by pressing: add form from project menu.
In vb there are two types of controls intrinsic control and ActiveX control. All intrinsic control
of VB placed on standard toolbox.
12
By Jayesh Gori
Form properties
Form events
Initialize
The Initialize event is the first event of a form when the program runs. This event is raised
even before the actual form window is created. You can use this event to initialize form's
properties
Example
Private Sub Form_Initialize()
Label1.Caption = "form is initialize"
End Sub
13
By Jayesh Gori
Load
After the Initialize event, Load event fires when the Form is loaded in the memory. This
Form event is invoked for assigning values to a control's property and for initializing
variables.
Resize
After the Load event, the form receives the Resize event. The form's Resize event is also
raised when you resize the form either manually or programmatically.
After the Resize event, Activate event fires. While working with multiple forms, the Activate
event fires when the form becomes an active form in the current application, and the
Deactivate event fires when the other form becomes the active Form.
Unload
The Unload event fires when the Form unloads. You can use this event to warn the user
that data needs to be saved before closing the application.
14
By Jayesh Gori
Label
This is probably the first control you will master. It is used to display static text, titles and
screen output from operations. The important properties to remember:
15
By Jayesh Gori
Text box
The text box is the standard control for accepting input from the user as well as to display the
output. It can handle string (text) and numeric data but not images or pictures. Text box controls
offer a natural way for users to enter a value in a program. For this reason they tend to be the
most frequently used controls in windows applications.
Text
This property is useful to display text to the user and get the value of text.
MaxLength
Returns or sets a value indicating whether there is a maximum number of characters that
can be entered in the TextBox control and, if so, specifies the maximum number of
characters that can be entered.
Multiline
Returns or sets a value indicating whether a Textbox control can accept and display
multiple lines of text. Read only at run time.
Scrollbar
Returns or sets a value indicating whether an object has horizontal or vertical scroll bars.
Read only at run time.
Password Char
Returns or sets a value indicating whether the characters typed by a user or placeholder
characters are displayed in a Textbox control; returns or sets the character used as a
placeholder.
16
By Jayesh Gori
Locked
Returns or sets a value that determines whether the control can be edited or not.
Alignment
This property is used to set the alignment of the text. By using this property text can be
aligned right, left or center. By default this property is left alignment.
Cause Validation
Returns or sets a value that determines whether the Validate event will occur on a second
control from which the focus is being shifted.
SelStart
This property will returns or sets the number of characters selected.
SelLength
This property will returns or sets the starting point of text selected; indicates the position of the
insertion point if no text is selected.
SelText
This property will returns or sets the string containing the currently selected text; consists of a
zero-length string ("") if no characters are selected.
Events
Textbox supports all keyboard events, MouseEvents, Focus. Change.
Methods
17
By Jayesh Gori
Move, SetFocus, Refresh,ZOrder.
ListBox
A list box control displays a list of items from which the user can select one or more.
If the number of items exceeds the number that can be displayed, a scroll bar is
automatically added to the list box control.
You can use a list box control when you have sufficient space on form.
Properties
List
Returns or sets the items contained in a control's list portion. The list is a string array in
which each element is a list item.
List1.List(0) = "Apple"
MsgBox "Selected item : " & List1.List(List1.ListIndex)
ItemData
Returns or sets a specific number for each item in a ComboBox or ListBox control.
object.ItemData(index) [= number]
The ItemData property is an array of long integer values with the same number of items
as a control's List property. You can use the numbers associated with each item to
identify the items. For example, you can use an employee's identification number to
identify each employee name in a ListBox control. When you fill the ListBox, also fill
the corresponding elements in the ItemData array with the employee numbers.
List1.AddItem ("Ronit")
18
By Jayesh Gori
List1.ItemData(1) = 22
End Sub
Column
Returns or sets a value that determines whether a ListBox control scrolls vertically or
horizontally and how the items in the columns are displayed. If it scrolls horizontally, the
Columns property determines how many columns are displayed.
Sorted
Returns a value indicating whether the elements of a control are automatically sorted
alphabetically. By default this property is false.
Style
This is the style to display item in listbox it may be ‘0 - Standard’ or ‘1 - checkbox’.
MultiSelect
Returns or sets a value indicating whether a user can make multiple selections in a
ListBox control and how the multiple selections can be made. It may be ‘0 – None’ or ‘1
– Simple’ or ‘Extended’.
Setting Description
0 (Default) Multiple selection isn't allowed.
1 Simple multiple selection. A mouse click or
pressing the SPACEBAR selects or deselects
an item in the list.
2 Extended multiple selections. Pressing SHIFT
and clicking the mouse or pressing SHIFT and
19
By Jayesh Gori
one of the arrow keys (UP ARROW, DOWN
ARROW, LEFT ARROW, and RIGHT
ARROW) extends the selection from the
previously selected item to the current item
Selcount
This is the runtime property that returns the number of selcted item in the list.
Selected
This is the runtime only property that is an array of true or false vales corresponding to
the item selected in the list.
Example
Dim i As Integer
i = Val(Text2.Text)
If (i < lstFruit.ListCount) Then
lstFruit.Selected(i) = True
End If
Text
This is the runtime and read only property. That will display selected item.
Example
MsgBox "lSelected item is" & lstFruit.Text
ListIndex
Returns or sets the index of the currently selected item in the control. Not available at
design time.
Example
Private Sub cmdList_Click()
MsgBox "Selected Item's Index is." & lstFruit.ListIndex
20
By Jayesh Gori
End Sub
NewIndex
This property returns the index of the item most recently added to a listbox control. This
is runtime property.
Example :
Private Sub Command1_Click()
List2.AddItem ("Apple")
MsgBox "New genereted item index is " & List2.NewIndex
End Sub
ListCount
This property returns the number of the items in a list control. This is runtime property.
Example
Private Sub cmdTotal_Click()
MsgBox "Total Item " & lstFruit.ListCount
End Sub
Events
Listbox supports all keyboard events, Mouse Events, Focus Events.
Methods
Move, SetFocus, Refresh,ZOrder. AddItem, RemoveItem and Clear
Combo Box
The combo box is similar to the list box.
A ComboBox control combines the features of a textbox and listbox that is user can
enter information in the text box portion or select an item from the list box portion of the
control.
A combo box includes a text box on top of a list box and only allows selection of one
item.
Combo box have text property that is available at design time while Text property of list
box is available at run time only.
21
By Jayesh Gori
Style
It is style of combo to be displayed to user. It may be ‘0-Dropdown combo’ or ‘1- Simple
combo’ or ‘2 – dropdown list’
SelStart
This property will returns or sets the number of characters selected.
SelLength
This property will returns or sets the starting point of text selected; indicates the position of the
insertion point if no text is selected.
SelText
This property will returns or sets the string containing the currently selected text; consists of a
zero-length string ("") if no characters are selected.
List
Returns or sets the items contained in a control's list portion. The list is a string array in
which each element is a list item.
22
By Jayesh Gori
ItemData
Returns or sets a specific number for each item in a ComboBox or ListBox control.
Sorted
Returns a value indicating whether the elements of a control are automatically sorted
alphabetically. By default this property is false.
ListIndex
Returns or sets the index of the currently selected item in the control. Not available at
design time.
NewIndex
This property returns the index of the item most recently added to a listbox control. This
is runtime property.
ListCount
This property returns the number of the items in a list control. This is runtime property.
Locked
Returns or sets a value indicating whether a control can be edited.
23
By Jayesh Gori
COMMON PROPERTIES FOR INTRINSIC CONTROLS
Name
This property is useful to set the name of the control. Using this property you can identify
control at design time or runtime.
Syntax
object.Name
Where object represents any intrinsic control.
The default name for new objects is the kind of object plus a unique integer. For example, the
first new Form object is Form1, Texbox1 etc.
An object's Name property must start with a letter and can be a maximum of 40 characters. It
can include numbers and underline (_) characters but can't include punctuation or spaces.
Appearance
This property is useful to set look of control.
Syntax
object.Appearance
Settings
The Appearance property settings are:
Setting Description
0 Flat. Paints controls and forms without visual effects.
1 (Default) 3D. Paints controls with three-dimensional effects. This
property is default.
Width
This property is used to set the width of the control.
Syntax
object.Width [= number]
Height
This property is used to set the height of the control.
Syntax
object.Height [= number]
Left
24
By Jayesh Gori
This property is used to sets the distance between the internal left edge of an object and the left edge of
its container (Form). object.Left [= value]
Top
This property is use to sets the distance between the internal top edge of an object and the top edge of
its container (Form).
object.Height [= value]
For the CommonDialog and Timer controls, these properties aren't available at run time.
This example sets the size of a form to 75 percent of screen size and centers the form when it's loaded.
Private Sub Form_Click()
Width = Screen.Width * 0.75 ' Set width of form.
Height = Screen.Height * 0.75 ' Set height of form.
Left = (Screen.Width - Width) / 2 ' Center form horizontally.
Top = (Screen.Height - Height) / 2 ' Center form vertically.
End Sub
Visible
This property is use to sets a value indicating whether an object is visible or hidden. Default value of
property is true.
Syntaxobject.Visible [= boolean] Eg. lblMsg.Visible = False
The settings for boolean are:
Setting Description
True (Default) Object is visible.
False Object is hidden.
Enable
Returns or sets a value that determines whether a form or control can respond to user-generated events.
Syntax
object.Enabled [= boolean]
The settings for boolean are:
Setting Description
True (Default) Allows object to respond to
events.
25
By Jayesh Gori
False Prevents object from responding to
events.
This example enables a CommandButton control whenever a TextBox control contains text.
Font
This property is use to set font attributes like font name, font size, font style etc.
Backcolor
This property is use to set background color of the control.
Forecolor
This property is use to set background color of the control.
ToolTipText
This property is use to set tool-tip text for the control.
Tabstop
This property is useful to set whether control can got focus by pressing tab key. By default the property
will be true. But if we set it false then control cannot got focus using tab key.
Tabindex
Tabindex is useful to set tab order of control. This property may be integer.
Tag
26
By Jayesh Gori
This is extra property of control using which user can store extra information related to program or
control.
Index
This property is use to identify control in control array.
Mouse pointer
This property is use to set mouse pointer for the control. By default this property is 0-default. If you
want to select other mouse pointer then you can select other mouse pointer.
Mouse icon
This property is useful to set custom mouse pointer for this we have mouse pointer property 99-custom.
The GUI aspects of VB programming involves the use of the various controls that are available in
the toolbox (there are intrinsic controls, which appear in the toolbox as soon as you open a new
VB project, as well as additional "ActiveX" controls that can be added in through the Project ->
Components menu).
With controls come properties (a set of variables that describe the appearance, behavior, and
other aspects of the control), methods (procedures built into a control that tell the control how to
do things), and events (actions that occur in your program).
Properties, methods, and events common to most controls are described in the tables below.
Common Properties of Visual Basic Controls
Every object, such as a form or control, has a set of properties that describe it. Although this set isn't identical for
all objects, some properties (such as those listed in the table below) are common to most controls.
You can see every design-time property for a given control by looking at the Properties window in the IDE (some
controls have properties that are available only at run-time
Property Description
Appearance Specifies whether an object's border appears flat or with a 3D look.
Align or Alignment For controls displaying text, specifies whether text is left, center, or right-aligned.
For controls such as a PictureBox or ToolBar, specifies how the control itself is
aligned on the form (top, bottom, left, or right).
BackColor Specifies the background color of the control.
BorderStyle Generally, specifies whether or not a control has a border. For the Form itself,
the type of border can be specified.
27
By Jayesh Gori
Caption or Text The string of text that is to be displayed in the control.
Enabled Determines whether or not the control can respond to user-generated events.
Font For controls displaying text, specifies the font (name, style, size, etc.) to be
applied to the displayed text.
ForeColor Specifies the color of text or graphics to be displayed in the control.
Height Specifies the height of the control. The default unit is the twip, which is 1/1440 of
an inch.
Index Specifies the element number of a control if the control is a member of a control
array.
Left Specifies the distance between the internal left edge of a control and the left
edge of its containter.The default unit is the twip, which is 1/1440 of an inch.
Name The string value used to refer to the control in code.
Picture Specifies the graphic to be displayed in the control.
TabIndex Specifies the tab order of a control within its parent form,
TabStop Specifies whether or not the user can use the Tab key to give focus to the
control.
Tag A string containing extra data associated with the control.
ToolTipText Specifies text to be displayed when the mouse is paused over the control.
Top Specifies the distance between the internal top edge of a control and the top
edge of its containter.The default unit is the twip, which is 1/1440 of an inch.
Visible Specifies whether the control is visible or hidden,
Width Specifies the width of the control. The default unit is the twip, which is 1/1440 of
an inch.
Methods are blocks of code designed into a control that tells the control how to do things, such as move to
another location on a form.
Just as with properties, not all controls have the same methods, although some common methods do exist, as
shown in the table below:
Method Description
Move Changes an object's position in response to a code request
Refresh The Refresh method causes the control to be redrawn
SetFocus Gives focus to the object specified in the method call
ZOrder Determines the order in which multiple objects appear onscreen
28
By Jayesh Gori
Move Method
If a control supports Left, Top, Width, and Height properties, it also supports the Move method, through
which you can change some or all four properties in a single operation. The following example changes
three properties: Left, Top, and Width.
SetFocus Method
The SetFocus method moves the input focus on the specified control. You need to call this
method only if you want to modify the default Tab order sequence that you implicitly
create at design time by setting the TabIndex property of the controls on the form.
A potential problem with the SetFocus method is that it fails and raises a run-time error if
the control is currently disabled or invisible. For this reason, avoid using this method in
the Form_Load event()
29
By Jayesh Gori
Refresh Method
The Refresh method causes the control to be redrawn. You normally don't need to
explicitly call this method because Visual Basic automatically refreshes the control's
appearance when it has a chance (usually when no user code is running and Visual Basic
is in an idle state). But you can explicitly invoke this method when you modify a
control's property and you want the user interface to be immediately updated:
30
By Jayesh Gori
Common Events of Visual Basic Controls
Events are what happen in and around your program. For example, when a user clicks a button, many events
occur: The mouse button is pressed, the Command Button in your program is clicked, and then the mouse button
is released.
Events common to most VB controls are described in the table below.
Change event
The Change event is the simplest event offered by Visual Basic: Whenever the contents of a
control change, Visual Basic fires a Change event.
TextBox and ComboBox controls raise a Change event when the user types something in the
editable area of the control. (But be careful, the ComboBox control raises a Click event when
the user selects an item from the list portion rather than types in a box.)
The Change event also fires when the contents of the control are changed through code.
Example
Private Sub Text1_Change()
Text2.Text = Text1.Text
End Sub
31
By Jayesh Gori
DragDrop Event
Occurs when a drag-and-drop operation is completed as a result of dragging a control over an object and
releasing the mouse button or using the Drag method with its action argument set to 2 (Drop).
Text2.BackColor = vbGreen
End Sub
DragOver
Occurs when a drag-and-drop operation is in progress. You can use this event to monitor the mouse pointer as it
enters, leaves, or rests directly over a valid target.
Click event
Click event occurs when the user presses and then releases a mouse button over an object. It can also occur
when the value of a control is changed.
For a Form object, this event occurs when the user clicks either a blank area or a disabled control. For a control,
this event occurs when the user does the following:
Clicks a control with the left or right mouse button. With a CheckBox, CommandButton, Listbox, or
OptionButton control, the Click event occurs only when the user clicks the left mouse button.
Selects an item in a ComboBox or ListBox control, either by pressing the arrow keys or by clicking the
mouse button.
Syntax
Private Sub Form_Click( )
The Click event syntax has these parts:
Example
32
By Jayesh Gori
Double click
Double click event occurs when the user presses and releases a mouse button and then presses and releases it
again over an object.
For a form, the DblClick event occurs when the user double-clicks a disabled control or a blank area of a form.
For a control, it occurs when the user:
Syntax
Example
This event occurs when the mouse is clicked, released or moved on a control respectively. All of them receive
the same set of parameters, the state of mouse buttons, the state of Shift/Ctrl/Alt keys and x and y coordinates of
mouse cursor.
Syntax
Button Returns an integer that identifies the button that was pressed (MouseDown) or released
(MouseUp) to cause the event. The button argument is a bit field with bits corresponding
to the left button (bit 0), right button (bit 1), and middle button (bit 2). These bits
correspond to the values 1, 2, and 4, respectively. Only one of the bits is set, indicating
the button that caused the event.
33
By Jayesh Gori
shift Returns an integer that corresponds to the state of the SHIFT, CTRL, and ALT keys when the
button specified in the button argument is pressed or released. A bit is set if the key is down. The
shift argument is a bit field with the least-significant bits corresponding to the SHIFT key (bit 0),
the CTRL key (bit 1), and the ALT key (bit 2 ). These bits correspond to the values 1, 2, and 4,
respectively.
x, y Returns a number that specifies the current location of the mouse pointer. The x and y
values are always expressed in terms of the coordinate system set by the ScaleHeight,
ScaleWidth, ScaleLeft, and ScaleTop properties of the object.
Example 1
Example 2 MouseMove
Example 3 MouseUp
Private Sub Label1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
Print "MouseUp Occurred"
Print Button
Print Shift
End Sub
Got Focus
Occurs when an object receives the focus, either by user action, such as tabbing to or clicking the object,
or by changing the focus in code using the SetFocusmethod.
A form receives the focus only when all visible controls are disabled.
Lost Focus
Occurs when an object loses the focus, either by user action, such as tabbing to or clicking another
object, or by changing the focus in code using the SetFocusmethod.
These events fire whenever the end user presses a key while a control has the input focus.
The exact sequence is as follows: KeyDown (the users presses the key), KeyPress (Visual Basic
translates the key into an ANSI numeric code), and KeyUp (the user releases the key).
Only keys that correspond to control keys (Ctrl+x, BackSpace, Enter, and Escape) and printable
characters activate the KeyPress event.
For all other keys including arrow keys, function keys, Alt+x key combinations, and so on this event
doesn't fire and only the KeyDown and KeyUp events are raised.
35
By Jayesh Gori
The KeyUp and KeyDown events report the exact physical state of the keyboard itself:
A key is pressed down (KeyDown) and a key is released (KeyUp). In contrast, the KeyPress event does
not report the state of the keyboard directly — it doesn't recognize the up or down state of the key, it
simply supplies the character that the key represents.
The KeyPress event is the simplest of the three. It's passed the ANSI code of the key that has been pressed by
the user, so you often need to convert it to a string using the Chr$() function:
Part Description
keycode A key code, such as vbKeyF1 (the F1 key) or vbKeyHome (the HOME key). To
specify key codes, use the constants in the Visual Basic (VB) object libraryin
the Object Browser.
shift An integer that corresponds to the state of the SHIFT, CTRL, and ALT keys at the
time of the event. The shift argument is a bit field with the least-significant bits
corresponding to the SHIFT key (bit 0), the CTRL key (bit 1), and the ALT key (bit
2 ). These bits correspond to the values 1, 2, and 4, respectively.
Example of keypress
Example of keydown
Key up
Private Sub Text1_KeyUp(KeyCode As Integer, Shift As Integer)
MsgBox "keyup reaised.."
End Sub
Important Questions
38
By Jayesh Gori