Sei sulla pagina 1di 25

DEPARTMENT O F COMPUTER SCIENCE AND APPLICATIONS

VISUAL PROGRAMMING
UNIT -2

BUILDING THE USER INTERFACE:

TOOL BOX:
A toolbox contains number of controls. These controls are used to create a simple application. It
contains 21 controls. They are
Text Box Picture Box Label Box Option Button
Frame Control List Box Combo Box Data Control
H Scroll Bar V Scroll Bar Command Button Check Box
Drive List Box. Dir Control File List Box Line Control
Shape Control Image Control OLE Timer Control &
Pointer

Text Box
Text box control is a versatile control. It can be used for getting the input from the user and also
display the result. It is called as Edit field or Edit control.

Picture Box
It can display a graphic from a bitmap, icon or metafile as well as enhanced metafile, JPEG or
GIF files.
Label Box
It allows you to display text that you don't want the user to change, such as caption under a
graphics.
Option Button
It allows you to display the multiple choices from which the user can choose only one option.

Frame Control
The frame control allows you to create graphical or functional grouping controls.
To group controls, draw the frame first and then draw controls inside the frame.
List Box
List box displays a list of items. It can occupy some space on the form.
Combo Box
Combo box is also used to display the items. But it can display a single item at a time. It can
occupy a less space on the screen.

Data Control
Data control provides access to database through controls on your form.
H Scroll Bar (Horizontal Scroll Bar)
Provides a graphical tool for quickly navigating through a long list of items or a large amount of
information for indicating the current position on a scale, or as an input device or indicator of speed or
quantity.
V Scroll Bar (Vertical Scroll Bar)
Provides a graphical tool for quickly navigating through a long list of items or a large amount of
information for indicating the current position on a scale, or as an input device or indicator of speed or
quantity.
Command Button
Creates a button that the user can choose to carry out a command. The user will click on this
button and the computer will perform the task associated with the button.
Check Box
It allows you to display the multiple choices from which the user can choose any number of
items.
Drive List Box, Directory List Box & File List Box
These controls are used to display available Drives, Directories and Files. The user can select a
valid Drive on his system. The user can see a hierarchical structure of directories and files.
Line control and Shape control
These controls are used to draw lines, square, circles, rectangles and etc.

Image control
It is very similar to the picture box control. Stretch property is available in Image control. So we
can easily resize the images.

OLE (Object Linking & Embedding)


This control allows you to link your program to another object or program like as Ms Word,
Internet Explorer, and Ms Word etc.

Timer control
It is a very important control. It is used for time-related processing. It is mainly used in the auto
save option.

CREATING CONTROLS:

 Move the mouse pointer to the tool that the user wants to use and click
 Move the mouse pointer to the form and draw the control
 Hold the mouse button down and drag the mouse to create the object
 Use eight little boxes called sizing handles to resize the control
 Locating controls only at grid points is called the aligning to the grid or snapping to the grid
Working with a control already on a form
User can also cut and paste controls using edit menu when they paste it appears on the top left
hand corner of the form
Resizing existing control
 Use the properties window to adjust the width and height properties or
 Work with the sizing handles
Sizing handles

Moving an existing control


 Move the pointer anywhere inside the control, click the left mouse button and hold it down Drag
the mouse until the control is at the location the user want it to be and then release the left button.
 For finer control movement select the control use ctrl + arrow key to move the control one grid
mark at a time or adjust the left and top properties.

Using double click shortcut for creating controls

Double click on any of the toolbox icons, matching control appers in the center of the screen
To create an application with three command buttons dbl click on the command button icons three times
Click on the tool it will create command buttons in the center of the screen.
Working with Multiple controls:
 Select each control by moving the mouse pointer to it and holding down the left mouse button
while pressing CTRL.
 Move the mouse pointer to any place outside the selected controls and click.

The alignment used for a group of controls is determined by the control in the group with the black sizing
handles and this is the last control selected in the group.
Choose Format->Align->Left all the controls will move to match up with the command2 control.

Locking controls:
Lock the controls by unnecessarily moving properly positioned controls.
 Format->Lock Controls or
 Lock Control tool from the toolbar

Deleting Controls:
To delete a control:
 Move the mouse pointer until it is inside the control, and click the left mouse button to select it.
 Press DEL or Open Edit menu->Choose Delete option by pressing ALT+ E,D.

THE NAME (CONTROL NAME) PROPERTY


This property determines the name VB uses for the event procedures the user write to
make the control respond to the user.

To change the height of the current form type


Height=5000 or
Me.Height=5000 or
Form1.height=5000
All the above represent the current working form.

If the user change the name of the form as Student then


Student.height=5000
To change the height of a command button whose name property is addition then
Addition. Height =250

Microsoft suggests using a prefix to start the name of any control.For command button the prefix is cmd.

Eg:
Private sub cmdaddition_click ()

End Sub

Rules for control name:


 Must begin with a letter
 After that, use any combination of letters, digits, and underscores.
 Name cannot be longer than 40 characters.

PROPERTIES OF COMMAND BUTTONS

Command Button properties

Property Description
Name The name of the object so you can call it at runtime
This specifies the command button's background color. Click the BackColor's palette
BackColor down arrow to see a list of common Windows control colours, you must change this to the
style property from 0 - standard to 1 - graphical
Cancel Determines whether the command button gets a Click event if the user presses escape
Caption Holds the text that appears on the command button.
Determins if the command button responds to an enter keypress even if another control has
Default
the focus
Determines whether the command button is active. Often, you'll change the enable
Enable
property at runtime with code to prevent the user pressing the button
Font Produces a Font dialog box in which you can set the caption's font name , style and size.
Height Positions the height of the object - can be used for down
Left Positions the left control - can be used for right
MousePointer If selected to an icon can change the picture of the mouse pointer over that object
Hold's the name of an icon graphic image so that it appears as a picture instead of a Button
Picture
for this option to work the graphical tag must be set to 1
This determins if the Command Button appears as a standard windows dialog box or a
Style
graphical image
Tab index Specifies the order of the command button in tab order
Whether the object can be tabbed to ( this can be used in labels which have no other
Tab Stop
function )
If the mouse is held over the object a brief description can be displayed (for example hold
Tool Tip Text
your mouse over one of the above pictures to see this happening
Visible If you want the user to see the button/label select true other wise just press false
Width Show the width of the object

SIMPLE EVENT PROCEDURES FOR COMMAND BUTTONS


Double click a control or press F7 to go to code window after that select the required event
for the command button and write the procedure for it. For example the command button shown below
has the name property as CmdClickMe and the code written for it is (print “KSR College” ) and the event
is Click.
OTHER EVENTS FOR COMMAND BUTTONS:

Events

GotFocus

Occurs when the CommandButton gets focus either from the Tab key, when it is clicked on by
the user or by using the SetFocus method.

KeyDown, KeyUp

KeyCode As Integer, Shift As Integer

When the user presses a keyboard key down or releases a key, these events occur.

Private Sub Command1_KeyDown(KeyCode As Integer, Shift As Integer)


If KeyCode = vbKeyBack Then
MsgBox "You pressed the backspace key!"
End If
End Sub
The Shift argument contains the value of the Shift, Control and Alt keys. This is useful for
performing a different action when one of these keys is pressed in combination with another e.g. pressing
'A' would be different to pressing 'Ctrl+A'.

Constant Value Description


vbShiftMask 1 Shift key
vbCtrlMask 2 Ctrl key
vbAltMask 4 Alt key

If a combination of these keys are pressed, the Shift argument will contain the sum of all keys pressed e.g.
Ctrl+Alt would be 6.

Private Sub Command1_KeyDown(KeyCode As Integer, Shift As Integer)


If Shift = vbCtrlMask + vbShiftMask Then
If KeyCode = vbKeyA Then
MsgBox "You pressed the Ctrl+Shift+A key combination!"
End If
End If
End Sub

KeyPress

KeyAscii As Integer

This event works differently to the KeyDown and KeyUp events in that it detects the actual character (as
the ANSI keycode) that is pressed rather than the keyboard key. E.g.:

Key Pressed Result


s 115
Shift Nothing
Space 32

You can use the Chr function to convert the code into a letter e.g. Chr(KeyAscii). If KeyAscii is set to 0
in this event, this makes the program act as if the key was never pressed.

LostFocus

Occurs when the CommandButton loses focus.


MouseDown, MouseUp

Button As Integer, Shift As Integer, X As Single, Y As Single

This event occurs when a mouse button is pressed down or released over a CommandButton.

Private Sub Command1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)


If Button = vbMiddleButton Then
MsgBox "The middle button was pressed on the CommandButton"
End If
End Sub

The Button argument returns one of the following possible values:

Constant Value Description


vbLeftButton 1 Left mouse button
vbRightButton 2 Right mouse button
vbMiddleButton 4 Middle mouse button

The Shift argument works the in same the same way as in the KeyDown and KeyUp events. The
X and Y arguments return the position of the cursor in relation to the CommandButton i.e. the coordinates
of the very top-left of the CommandButton are 0, 0.

The MouseDown event occurs before the Click event and the MouseUp event occurs after the
Click event.

THE IMAGE CONTROL

Image controls hold pictures.


They can also be used for creating toolboxes

Image controls can be used to display icons or pictures created with the program such as Microsoft
paintbrush. They can also hold windows metafiles, JREGs or Gif files.
Image controls are far less complex than Picture Box controls. They don't support graphical
methods or the AutoRedraw and the Clip Controls properties, and they can't work as containers, just to
hint at their biggest limitations.

Nevertheless, you should always strive to use Image controls instead of Picture Box controls
because they load faster and consume less memory and system resources. Remember that Image controls
are windowless objects that are actually managed by Visual Basic without creating a Windows object.
Image controls can load bitmaps and JPEG and GIF images.

It is used to display a graphic. An Image control can display a graphic from a bitmap, Icon, or
metafile, as well as enhanced metafile, JPEG, or GIF files.
Property Description Data Value
Left, Top This property determines the
distance between the Image
Control and the left edge and
top of the container (form),
respectively.
BorderStyle Returns/sets the border style  No border (setting =0)
of the object  (Default) Fixed Single
border (Setting=1)
Stretch Returns or sets a value  True-The graphic resizes
indicating whether a graphic to fit the control.
resizes to fit the size of an  False-(Default) The
Image control control resizes to fit the
graphic.
Picture Returns or sets a graphic to be Picture(Bitmap, metafile,
displayed in a control. Icon etc)
TEXTBOXES

They are the primary methiods of getting input and displaying the output in VB. They trat the user input
as number and this means getting numeric input to VB program requires transforming a string of digits
into number by using built in function or automatic type conversion
LABELS:

It is used to display information about the controls present near by. It is used to identify a textbox
or other control by describing its content.

Properties for Labels

1. Caption Property:
To display text on a label control, set its Caption property.

2.BackColor Property
Sets the back color of the label

3.ForeColor Property
Sets the fore color (color of the text that is displayed) of the label

4.Visible Property
Makes the labels appear and disappear by setting the value true or false.

5. Alignment
Return/sets the alignment of a control’s text. By setting the values as
 0-(default) left-aligned
 1-right-aligned
 2-center
6. BorderStyle
Returns/sets the border style of the object. By setting the values as
 No border (setting =0)
 (Default) Fixed Single border (setting =1)
7. BackStyle
Determines whether the label is transparent or opaque.

8.Autosize
Determines whether a control is automatically resized to display its entire contents. By setting the values
as
 True- resized according to the contents
 False (default)-does not resizes.

9.WordWrap
Returns/sets a value that determines whether a control expands to fit the text in its caption. By setting the
values as
 True- wraps the contents
 False (default)-does not wraps the contents.
10.Usemnemonic
Returns/sets a value that specifies whether an ampersand (&) included in the text of the caption property
of the label control defines an access key. By setting the values as
 True-(Default)Any ampersand appearing in the text of the caption property causes the character
following the ampersand to become an access key. The ampersand itself is not displayed in the
interface of the label control
 False-Any ampersand appearing in the text of the caption property is displayed as an ampersand
in the interface of the Label control.

Some Event Procedures for Labels

Click event- it occurs on clicking the label.


Change event- it occurs when the contents of a control have changed.
DblClick event- it occurs on double clicking the label.
MouseDown-it occurs when the user presses the mouse button.
MouseUp events-it occurs when the user releases the mouse button.
MouseMove event-it occurs when the mouse is moved towards the label.

MESSAGE BOX
The message box displays a message in a dialog box, waits for the user to click a button, and
returns an integer indicating which button the user clicked.

Syntax:

Msgbox(Prompt,[buttons],[title])
Prompt-String expression displayed as the message in the dialog box.
Buttons-Numeric Expression that is the sum of values specifying the number and type of buttons to
display, the icon style to use, the identity of the default button, and the modality of the message box. If
omitted, the default value for buttons is 0.
Title- String Expression displayed in the title bar of the dialog box. If omitted, the application name is
placed in the title bar.

The button argument settings are:

Constant Values Description


VbOkOnly 0 Display ok button only
VbOkCancel 1 Display Ok and Cancel
buttons
VbAbortRetryCancel 2 Display Abort, Retry, Cancel
VbYesNoCancel 3 Display Yes, No, Cancel
VbYesNo 4 Display Yes, No
VbRetryCancel 5 Display Retry, Cancel
VbCritical 16 Display critical message icon
VbQuestion 32 Display Warning query icon
VbExclamation 48 Display Warning message
icon
VbInformation 64 Display Information message
icon.
VbDefaultButton1 0 First Button is default
VbDefaultButton2 256 Second Button is default
VbDefaultButton3 512 Third Button is default
VbDefaultButton4 768 Fourth Button is default

The first group of values (0-5) describes the number and type of buttons displayed in the dialog box; the
second group(16,32,48,64) describes the icon style; the third group(0,256,512,768) determines which
button is default. When adding numbers to create a final value will be returned.

For Example:

Private Sub Command1_Click ()


Dim Result as Integer
Result =Msgbox (“Hello”, VbOkCancel+VbCritical+VbDefaultButton1,”Sample”)
End Sub

THE GRID:
Grid is important for accurately positioning controls. In order to control the grid, choose Tools|Options
(ALT+T, O), and then go to the General page on the options dialog box, as shown in the figure.

The properties we can control are described next.


Show Grid –We can turn the grid on or off by changing the Show Grid setting. The default setting is on.
Grid Width, Grid Height Boxes- The width and Height text boxes allows setting the distance (in twips)
between grid marks. The default is 120 twips.
Align Controls to Grid- This check box determines whether controls automatically move to the next grid
mark or whether they can be placed between grid marks.

Anatomy of the Code Window:


The title bar of the code window contains the name of the Project and Form name. Next there
are two combo boxes. One holds the text “Form” and the other holds the text “Load”.

Code Window Event procedure

Object Procedures

This means that form is the name of the object and load is the event that you want to write the
code for. Click the down arrow button and the Drop Down list box will display all the controls that have
been placed in the form.
If you intend to write the Command1, then select it from the list by clicking on it. Now click on
the Down arrow button on the other Drop down control. This will list all the events related to the selected
object. The lines given below provide a framework within which you can enter the code.

Private Sub Command1_Click ()

End Sub

The Private means that the variables declared and the code used here can be used only by this
function. Then we have the word Sub. This is short for Sub-routine or Function. Command1_Click() is
the name of the function which is self explanatory. End Sub means end of this subroutine.
Working with the Form-Click Event

 Move to the event drop-down list box on the right and click the down arrow.
 Move through the box until the user get to the click item.
 Select Form_Click event and click on it.

Then Visual Basic does the following:

 Gives the user a new event procedure template for the Form-Click event procedure
 Adds a dotted line between the Form_Load event and the click event.
 Moves the cursor to the blank line before the End Sub line in the click event procedure.

Output

When the user run the form and click once above the form it will show the following output
Comment Statements
These statements are statements that help to explain our code to people, but they are not processed by
visual Basic. They are also known remark statements.
There are two ways to indicate a comment statement.
 Using single quotation mark (‘)
 Using Rem keyword
For eg:
1. Private sub command1_click()
‘This is an example of comment statement using single quotes
End Sub
2. Private sub command1_click()
Rem This is an example of comment statement using Rem
End Sub

The End statement


When VB processes an End Statement, the program stops (i.e.). The program, which is presently
running, gets closed and cleared from memory.
There are ways to indicate an End statement
 Using End keyword
 Using Unload Me keyword
For e.g.
1.Private sub command1_click()
End
End Sub
2.Private sub command1_click()
Unload Me
End Sub

Variables

In Visual Basic, Variables are used to store values temporarily during the execution of an application.
Variables have a name (the word use to refer to the value the variable contains) and a data type (which
determines the kind of data the variable can store). Variable is a placeholder in memory for an unknown
value

Declaring Variables

To declare a variable is to tell the program about it in advance. Declare a variable with the Dim statement,
supplying a name for the variable:

Dim variablename [As type]

Variables declared with the Dim statement within a procedure exist only as long as the procedure is
executing. When the procedure finishes, the value of the variable disappears. In addition, the value of a
variable in a procedure is local to that procedure — that is, we can't access a variable in one procedure
from another procedure. A naming convention of a variable:

 Must begin with a letter.


 Can't contain an embedded period or embedded type-declaration character.

 Must not exceed 255 characters.

 Must be unique within the same scope, which is the range from which the variable can be
referenced — a procedure, a form, and so on.

The optional As type clause in the Dim statement allows us to define the data type or object type of the
variable that we are declaring. Data types define the type of information the variable stores. Some
examples of data types include String, Integer, and Currency

There are other ways to declare variables:

 Declaring a variable using the Public keyword makes it available throughout our application.

 Declaring a local variable using the Static keyword preserves its value even when a procedure
ends.

Implicit Declaration

In VB, don't have to declare a variable before using it. For example, we can write a function where we
don't eed to declare TempVal before using it:

Function SafeSqr(num)
TempVal = Abs(num)
SafeSqr = Sqr(TempVal)
End Function

Visual Basic automatically creates a variable with that name, which we can use as if we have explicitly
declared it. While this is convenient, it can lead to subtle errors in our code if we misspell a variable
name. For example, suppose that this was the function we wrote:

Function SafeSqr(num)
TempVal = Abs(num)
SafeSqr = Sqr(TemVal)
End Function

At first glance, this looks the same. But because the TempVal variable was misspelled on the next-to-last
line, this function will always return zero. When Visual Basic encounters a new name, it can't determine
whether we actually meant to implicitly declare a new variable or we just misspelled an existing variable
name, so it creates a new variable with that name.

Explicit Declaration

To avoid the problem of misnaming variables, we can stipulate that Visual Basic always warn us
whenever it encounters a name not declared explicitly as a variable.

To explicitly declare variables


 Place this statement in the Declarations section of a class, form, or standard module:

Option Explicit

–or–

From the Tools menu, choose Options, click the Editor tab and check the Require Variable
Declaration option. This automatically inserts the Option Explicit statement in any new modules,
but not in modules already created; therefore, we must manually add Option Explicit to any
existing modules within a project.

Data Types

Variant: By default Visual Basic variables are of variant data types. The variant data type can store
numeric, date/time or string data. We can also declare explicitly a variable as variant. When a variable is
declared, a data type is supplied for it that determines the kind of data they can store .The fundamental
data types in visual basic including variant are integer, long, single, double, string, currency.

String: It is used to hold characters. It can be single character or many. A variable holding a string is
called a string variable. One method of identifying variables of this type is to place a dollar sign ($) at the
end of the variable name: a$=’ABC’

Integer: It is used to hold relatively small integer values (between –32,768 and +32,767). One method of
identifying variables of this type is to place a percent sign (%) at the end of the variable name: a$=3

Long Integer: It is used to hold integer values (between –2,147,483,648 and 2,147,483,648). One method
of identifying variables of this type is to place a ampersand sign (&) at the end of the variable name:
a&=123456789

Single Precision: Just as there are two integer types for different size values, numbers with decimal
points have different variable types depending on how large and how accurate we want them to be. The
least accurate is called single precision. They have a decimal point, but of seven digits accuracy .It is used
to hold decimal values. One method of identifying variables of this type is to place a exclamation sign (!)
at the end of the variable name: a!=12.345

Double Precision: The double-precision data type is used when we need numbers with up to 16 places of
accuracy. These variables are mainly used in scientific calculations in Visual Basic. One method of
identifying variables of this type is to place a pound sign (#) at the end of the variable name: a#=12.345

Currency: This type can have 4 digits to the right of the decimal place and up to 15 to the left of the
decimal point. Arithmetic will be exact within this range. One method of identifying variables of this type
is to place a ‘at’ (@) at the end of the variable name: a@=12.345

Date: This type gives a convenient way to store both date and time information for any time between
midnight on January 1,100, to midnight on December 31, 9999. We need to surround any assignment to
date variables with two #’s, for example: Millennium= #January 1,2000#

Byte: It is used to hold between 0 and 255.This is a great convenience when we need to save space , and
it makes certain arrays much smaller .
Boolean: It is used to hold data either true or false .It is considered good programming practice to use this
data type rather than integers for True/False values.

Working with variables:

Scope and Lifetime of Variables


Local scope:
The value of the variable can be accessed only within a event procedure where it is declared.
Global scope: The value of the variable can be accessed by all the procedures present in the form
module.

Static: Variables have a lifetime in addition to scope. The values in module-level and public variables are
preserved for lifetime of an application whereas local variables declared with Dim, exist only while the
procedure in which they are declared is executing. The value of a local variable can be preserved using
Static keyword.

More on Strings
A String is simply a bunch of characters surrounded by double quotes.

String Concatenation
Concatenation of two Strings can be done using ampersand (&).For example:
Name1$=”Visual”
Name2$=”Basic”
Subject_name$=Name1 & Name2

MsgBox Subject_name
Output will be Visual Basic displayed using message box.

Fixed-Length Strings
A fixed-length string is a special type of string that plays an important role.These variables are created
using Dim statement .Here is an example:
Dim shortstring As String * 10
Dim strshort As String * 10
Both of these statements set up string variables However, this variable will always hold strings of length
10.If we assign a longer string to shortstring ,as shown below
shortstring=”antidisestablishment”
We will get is the same thing as:
Shortstring=”antidisest”As we can also see, the variable contains only the left ten characters of the value.
Similarly, if we assign a shorter string to shortstring, like this,
Shortstring=”a”
We still get a string of length 10,only this time the contents of the variable are padded on the right so that
the string is really stored in the same way as:
Shortstring=”a”
Thus, fixed-strings are “right padded” if necessary.

More on Numbers
We can use a decimal point, but if we assign such a number to an integer or long Integer variable, it will
automatically be rounded to an integer value. If we assign a number larger than the limits for the given
variable ,Visual Basic will give the user an error message at run time.
Here are some examples:
Number Acceptable in an assignment to a numeric
variable?
3001 Okay for all number variables
3000001 Okay for all but short Integer variables
30000.01 Okay for all but integer variables (rounded
off for them and for long integer variables)
3,001 Illegal because it uses a comma

The Numeric Operators

Operator Operation
+ Addition
- Subtraction (and used to denote negative
numbers)
/ Division
* Multiplication
^ Exponentiation
\ Integer division(this symbol is a backslash)
Mod The remainder after Integer division

Hierarchy of Operations:
The following list gives the order of operations:
 Exponentiation
 Negation (Making a number negative)
 Division and Multiplication
 Integer division
 The remainder (Mod) function
 Addition and Subtraction

Type Conversions

Text that we have entered in the text box is always considered as string. In order to perform arithmetic
operations on the values present in the text box, we need to convert the type of the value present in the
textbox explicitly. There are various functions present in the VB for type conversions.
Val function

VB has a function called Val that is a catch-all converter, and so VB programmers still often use to
convert a numeric string to a number .Val simply reads through the string until it encounters a non-
numeric character (or a second period). The number we get from it is determined by where it stopped
searching.

For Example
Val (“30something”)=30
Or,
Val (7.5%)=7.5
Because of its forgiving nature, it is better to use “C” conversion functions than Val function.

“C” Conversion functions


Using these functions we can able convert from any data type to other i.e. Integer into double and vice
versa
Conversion Function What it does
CInt Converts to an integer
CLng Converts to a long integer
CSng Converts to single precision
CDbl Converts to double precision
Ccur Converts to the currency type

Converting Numbers back to Strings


The Str () function is used to convert numeric value into string.
Str(123) =”123”
Str(123.4567) =”123.4567”
Str(-987654321) =”-987654321”

Constants
Constants, like variables, are named storage locations in memory with local, form, module, or global
scope. Visual Basic prevents the value of a constant from being changed during program execution. It
uses constants more efficiently than variables, so if we plan to use a value that never changes, we should
create a constant. To create a constant, we use the Const statement with the following syntax:
For example: Const A =10
A naming convention of a constant:

 Must begin with a letter.

 Can't contain an embedded period or embedded type-declaration character.

 Must not exceed 255 characters.


Input Boxes

Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a
String containing the contents of the text box.

Following is an expanded InputBox

Syntax :

variablename = InputBox (prompt[,title][,default][,xpos][,ypos][,helpfile,context])

variablename is a variant data type but typically it is declared as string, which accept the message
input by the users.

The arguments are explained as follows:

 Prompt - String expression displayed as the message in the dialog box. If prompt consists of more
than one line, the user can separate the lines using the vbCrLf constant
 Title - String expression displayed in the title bar of the dialog box. If the user omit the title, the
application name is displayed in the title bar
 default-text - The default text that appears in the input field where users can use it as his intended
input or he may change to the message he wish to key in.
 x-position and y-position - the position or the coordinate of the input box.
 The twp paratmeters helpfile and context are used together when the user have a help message
attached to the box.

Following example demonstrates the use of InputBox function

* Open a new project and save the Form as InputBox.frm and save the Project as InputBox.vbp
* Design the application as shown below.

Object Property Setting


Form Caption InputBox test

Name frmInputBox
The user
Label Caption
entered
Name
lbl1
Caption ( empty)
Label
Name lbl2

BorderStyle 1-Fixed Single


CommandButton Caption OK

Name cmdOK

Following code is entered in cmdOK_Click ( ) event

Private Sub cmdok_Click()


Dim ans As String
ans = InputBox("Enter something to be displayed in the label", "Testing", 0)
If ans = "" Then
lbl2.Caption = "No message"
Else
lbl2.Caption = ans
End If
End Sub

Save and run the application. As soon as the user click the OK button the user will get the following
InputBox
Here I have entered "Hello World" in text field. As soon as the user click OK the output is shown as
shown below

Potrebbero piacerti anche