GUI PROGRAMMING
UNIT - I
Programming Languages
A computer is a computational device which is used to process the data under the control of a
computer program. Program is a sequence of instruction along with data. While executing the
program, raw data is processed into a desired output format. These computer programs are
written in a programming language. There are five generation of Programming languages.They
are:
First Generation Languages :
These are low-level languages like machine language.
Second Generation Languages :
These are low-level assembly languages used in kernels and hardware drives.
Third Generation Languages :
These are high-level languages like C, C++, Java, Visual Basic and JavaScript.
Fourth Generation Languages :
These are languages that consist of statements that are similar to statements in the human
language. These are used mainly in database programming and scripting. Example of these
languages include Perl, Python, Ruby, SQL, MatLab(MatrixLaboratory).
Fifth Generation Languages :
These are the programming languages that have visual tools to develop a program. Examples
of fifth generation language include Mercury, OPS5, and Prolog.
Procedural Programming:
Procedural Programming can be defined as a programming model which is derived from
structured programming, based upon the concept of calling procedure. Procedures, also known
as routines, subroutines or functions, simply consist of a series of computational steps to be
carried out. During a program’s execution, any given procedure might be called at any point,
including by other procedures or itself.
Example: FORTRAN, ALGOL, COBOL, BASIC, Pascal and C.
Object Oriented Programming:
Object oriented programming can be defined as a programming model which is based upon the
concept of objects. Objects contain data in the form of attributes and code in the form of
methods. In object oriented programming, computer programs are designed using the concept
of objects that interact with real world. Object oriented programming languages are various but
the most popular ones are class-based, meaning that objects are instances of classes, which
also determine their types.
Example: Java, C++, C#, Python, PHP, JavaScript, Ruby, Perl, Objective-C, Dart, Swift, Scala.
Event Driven Programming:
Event-driven programming is a programming paradigm in which the flow of program
execution is determined by events - for example a user action such as a mouse click, key press.
In event-driven programming the program responds to these events. The order of the events
is determined by the user, not the program. VISUAL BASIC is one of the events driven
Programming Languages.
What is Visual Basic?
The word “Visual” refers to the way the Graphical User Interface (GUI) is designed. With
some programming languages you have to design the GUI’s by writing lots of code to describe
everything about the GUI (for example appearance, location of controls, how to display the
controls, etc). But with Visual Basic all you have to do is select the control you want and draw it
on the form. This is also known as object orientated programming. The word basic stands for
Beginners All-Purpose Symbolic Instruction Code which refers to the coding section of the
software. The actual code is very simple to use as it is just a large section of English word to do
a certain task.
The Visual Basic 6.0 programming environment.
The Visual Basic environment consists of eight main windows which are listed as follows and
explained in figure-1.
1. Menu Bar
Displays the commands you use to work with VB. Besides the standard File, Edit, View,
Window and Help menus, menus are provided to access functions specific to programming
such as project, Format, or Debug.
2. Toolbars
Provides quick access to commonly used commands in the programming environment. By
default the standard toolbars displayed when you start VB. additional toolbars for editing, form
design and debugging can be toggled on or off from the Toolbars command on the View menu.
3. Toolbox
Provides a set of tools that you use at design time to place controls on a form. In addition to
the default toolbox layout, you can create your own custom layouts by selecting Add Tab from
the context menu and adding controls to the resulting tab.
4. Project Explorer Window
List the forms and modules in your current project. A project is the collection of files you use
to build an application.
5. Properties Window
List the property settings for the selected form or control. A property is a characteristic of an
object, such as size, caption or color.
6. Form Window
Serves as a window that you customize to design the interface of your application. You add
controls, graphics and pictures to a form to create the look you want. Each form in your
application has its own form designer window.
7. Code Editor Window
Serves as an editor for entering application code. a separate code editor window is created
8. Form Layout Window
The Form Layout window allows you to position the forms in your application using a small
graphical representation of the screen.
Figure -1
CREATE YOUR FIRST PROGRAM WITH VISUAL BASIC 6.0
1. Click Window Start button-->All Programs --> Microsoft Visual Studio 6.0 --> Microsoft
Visual Basic 6.0
2. The New Project dialog box will appear. If it doesn't go up to the menu bar and select File ->
New Project
3. In the New Project dialog select Standard EXE, and click the Open Button. This will bring up
your new Project 1 application with Form1 visible.
4. Adding Command Button in the Form1 by Double click the button icon and it will create
a Command1 Command Button in the center of your form
5. To write the click event code double click on the Command1 button. This will bring up
the code editor and will automatically write the beginning code to handle the click event.
6. Write Your Code here in Code Window as per Shown Below
7. Run your newly created Visual Basic hello world program (Press F5).
8. Once the program is running click the Command1 button, you should see a message
box saying “Hello, World!” appear.
FINDING AND FIXING ERRORS
Error-Handling is a flexible feature of Visual Basic programming. When creating programs
sometimes there may be an Error which will disrupt the program flow and may terminate the
program. For successful programming errors need to be captured by using code and prompting
the user to take some action and then continue the program flow rather than terminating the
program.
Types of Errors
Many errors can occur when creating a program, the type of errors can be categorized into the
three following headings:
Syntax Errors
When writing code it is very important to adhere to the rules of the language. For
example, the following line of code will generate what is known as a Syntax error, because the
reserved word For has been spelt incorrectly.
Dim i As Integer
Far i = 1 To 5
MsgBox "Hello"
Next i
Logic Errors
These are the most difficult to detect and do not produce errors but do produce unexpected
results. For example, study the following code listing and determine the logic error:
Dim intNum, totNum As Integer 'Declare variables...
totNum = 0 'Initialize totNum variable
Do While intNum< 3 'Loop while intNum is less than three
totNum = totNum + intNum 'Running total on intNum
Loop
MsgBoxtotNum 'Display the total
The While loop runs infinitely and the MsgBox is NEVER executed. The reason for this is that
there is no code to exit the loop based on the condition of intNum being less than 3.
The intNum variable should have been initialized (for good practice)
and incremented or decrementedaccording to the condition of the loop. This is the Logic Error,
and although the code compiles and runs, the expected outcome does not occur. The revised
and correct listing for the above code is illustrated below:
Dim intNum, totNum As Integer 'Declare variables...
totNum = 0 'Initialize totNum variable
intNum = 0
Do While intNum< 3 'Loop while intNum is less than three
totNum = totNum + intNum 'Running total on intNum
intNum = intNum + 1 'Increment the value of intNum by 1
Loop
MsgBoxtotNum'Display the total
Run-time Errors
These are also very common, and are generated when the program compiles but
an error occurs which halts the program. Examples of the types of run-time errors are
illustrated below:
1. Accessing a file that does not exist
2. Dividing by zero
3. Storing values inside incompatible data types
4. Referencing objects that do not exist
The advantage of Visual Basic is that it allows you to take some action on an error, and the
program can terminate, continue on the next line after the error, or retry until the error is
resolved. This will be discussed in the next section below.
Controls in Visual Basic
The visual basic 6 controls are objects that are placed on the form. Even a form is a control
object. Each of the control objects has properties, methods, and events associated with them.
Properties are attributes that describe the type of control. Methods are functions performed by
the control object. A method is triggered due to some events such as mouse click, mouse over,
key press and so on.
The Form Object
The Form is where the user interface is drawn. It is central to the development of Visual Basic
applications.
Form Properties:
Appearance -Selects 3-D or flat appearance.
BackColor- Sets the form background color.
BorderStyle- Sets the form border to be fixed or sizeable.
Caption - sets the form window title.
Font -Sets font type, style, size.
ForeColor- Sets color of text or graphics.
Picture -Places a bitmap picture in the form.
Form Events:
Activate -Form_Activate event is triggered when form becomes the active window.
Click - Form_Click event is triggered when user clicks on form.
DblClick -Form_DblClick event is triggered when user doubleclicks on form.
Load -Form_Load event occurs when form is loaded. This is a good place to initialize
variables and set any runtime properties.
Form Methods:
Cls -Clears all graphics and text from form. Does not clear any objects.
Print - Prints text string on the form.
Examples
frmExample.Cls -clears the form
frmExample.Print "This will print on the form"
Control or object Description
Pointer Provides a way to move and resize the controls form
PictureBox Displays icons/bitmaps and metafiles. It displays text or acts as a visual
container for other controls.
Label Displays a text that the user cannot modify or interact with.
TextBox Used to display message and enter text.
Frame Serves as a visual and functional container for controls
CommandButton Used to carry out the specified action when the user chooses it.
CheckBox CheckBox control which is a part of anCheckBox group allows the user to
select more than one option from the available choices.
OptionButton OptionButton control which is a part of an option group allows the user to
select only one option even it displays mulitiple choices.
ListBox Displays a list of items from which a user can select one.
ComboBox Contains a TextBox and a ListBox. This allows the user to select an ietm
from the dropdown ListBox, or to type in a selection in the TextBox.
HScrollBar and These controls allow the user to select a value within the specified range of
VScrollBar values
Timer Executes the timer events at specified intervals of time
DriveListBox Displays the valid disk drives and allows the user to select one of them.
DirListBox Allows the user to select the directories and paths, which are displayed.
FileListBox Displays a set of files from which a user can select the desired one.
Shape Used to add shape (rectangle, square or circle) to a Form
Line Used to draw straight line to the Form
Image used to display images such as icons, bitmaps and metafiles. But less
capability than the PictureBox
Data Enables the use to connect to an existing database and display information
from it.
OLE Used to link or embed an object, display and manipulate data from other
windows based applications.
The following properties apply to most of the objects :
• Name : It sets the name of the control, through which you can access the control’s
properties and methods.
• Appearance : It can be 0 for a flat look or 1 for a 3-D look.
• Back Color : It sets the background color on which text is displayed or graphics are
drawn.
• Fore Color : It sets the foreground color
• Font : It sets the face, attribute, and size of the font used for the text on the control.
• Caption : It sets the text that is displayed on many controls that don’t accept input, for
example, the text on a Label control, the caption of a Command Button control.
• Text : It sets the text that is displayed on the controls that accept user input, for example,
the TextBox control.
• Width &Height : These properties set the control’s dimensions.
• Left &Top : These properties set the coordinates of the control’s upper-left corner,
expressed in the units of the container.
• Enabled : By default, this property’s value is True, which means that the control can get
the focus.
• Visible : Set this property to False to make a control invisible.
TextBox
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. A string entered
into a text box can be converted to a numeric data by using the function Val(text). The important
properties are
Locked - If this control is set to True user can use it else if this control is set to false the
control cannot be used
MaxLength - Specifies the maximum number of characters to be input. Default value is
set to 0 that means user can input any number of characters
Multiline - By setting this property to True user can have more than one line in the
TextBox
PasswordChar - This is to specify mask character to be displayed in the TextBox
Text Box Events:
Change :Triggered every time the Text property changes.
LostFocus :Triggered when the user leaves the text box. This is a good place to examine
the contents of a text box after editing.
GotFocus :Triggered when the user enter into the text box.
KeyPress :Triggered whenever a key is pressed. Used for key trapping, as seen in last
class.
Command Buttons
Command buttons are generally used to begin, interrupt, or end a particular process. A user will
often use a command button either by clicking it or by tabbing to it and pressing
Command Button Properties:
Appearance - Selects 3-D or flat appearance.
Cancel - Allows selection of button with Esc key (only one button on a form can have this
property True).
Caption - String to be displayed on button.
Default - Allows selection of button with Enter key (only one button on a form can have
this property True).
Text Box Output
Private Sub Command1_Click()
‘To add the values in text box 1 and text
box 2
Sum = Val(Text1.Text) +
Val(Text2.Text)
‘To display the answer on label 1
Label3.Caption = Sum
End Sub
The 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:
Alignment - text centered, left or right
Multiline- True or False - if True, you can have several lines of text, delimited by <CR> in
the label - by default, it is set to False
The PictureBox
The Picture Box is one of the controls that is used to handle graphics. It is best suited for
dynamic environments - for example, when doing animation.
PictureBox Properties
AutoSize - If True, box adjusts its size to fit the displayed graphic.
Font - Sets the font size, style, and size of any printing done in the picture box.
Picture - Establishes the graphics file to display in the picture box.
You can load a picture at design phase by clicking on the Picture property in the properties
window and select the picture from the selected folder. You can also load the picture at runtime
using the LoadPicture method. For example, the statement will load the picture grape.gif into
the picture box.
Picture1.Picture=LoadPicture ("C:\VBprogram\Images\grape.gif")
The Image Control
The Image Control is another control that handles images and pictures. It functions almost
identically to the pictureBox. However, there is one major difference, the image in an Image Box
is stretchable, which means it can be resized. This feature is not available in the PictureBox.
Similar to the Picture Box, it can also use the LoadPicture method to load the picture. For
example, the statement loads the picture grape.gif into the image box.
Image1.Picture=LoadPicture ("C:\VBprogram\Images\grape.gif")
The ListBox
A list box displays a list of items from which the user can select one or more items. If the
number of items exceeds the number that can be displayed, a scroll bar is automatically added.
List Box Properties:
Appearance :Selects 3-D or flat appearance.
List :Array of items in list box.
ListCount :Number of items in list.
ListIndex :The number position of the most recently selected item in list.If no item is
present in the list,ListIndex = -1.
MultiSelect :Controls how items may be selected (0-no multiple selection allowed, 1-
multiple selection allowed, 2-group selection allowed).
Selected :Array with elements set equal to True or False,depending on whether
corresponding list item is selected.
Sorted :True means items are sorted in Ascii order, else items appear in order added.
List Box Events:
Click :Event triggered when item in list is clicked.
DblClick :Event triggered when item in list is double-clicked.Primary way used to process
selection.
List Box Methods:
AddItem :Allows you to insert item in list.
Clear :Removes all items from list box.
RemoveItem :Removes item from list box, as identified by index of item to remove.
Examples
• lstExample.AddItem "This is an added item" adds text string to list
• lstExample.Clear clears the list box
• lstExample.RemoveItem 4 removes item with Listindex 4 from the list
Private Sub Form_Load( )
List1.AddItem “Lesson1”
List1.AddItem “Lesson2”
List1.AddItem “Lesson3”
List1.AddItem “Lesson4”
End Sub
The items in the list box can be identified by the ListIndex property, the value of the ListIndex
for the first item is 0, the second item has a ListIndex 1, and the third item has a ListIndex 2 and
so on
The ComboBox
The function of the Combo Box is also to present a list of items where the user can click and
select the items from the list.It is the combinations of Text Box and List Box. However, the user
needs to click on the small arrowhead on the right of the combo box to see the items which are
presented in a drop-down list.
Combo Box Properties:
• Combo box properties are nearly identical to those of the list box, with the deletion of the
MultiSelect property and the addition of a Style property. These can be set at design time by
changing the Style property of the object. This is illustrated below:
0 is the default Dropdown Combo. This consists of a text box and drop down list. Here
the user would select an item from the list or enter a value into the text box.
1 is the Simple Combo, this is a text box which does not have a drop down list. All the
elements will be shown by altering the size of the combo box by altering its Height
property.
2 is the Dropdown List which allows selection as a drop-down list.
Text Property - Text of most recently selected item
In order to add items to the list, you can also use the AddItem method. For example, if you
wish to add a number of items to Combo box 1, you can key in the following statements.
Private Sub Form_Load( )
Combo1.AddItem "Item1"
Combo1.AddItem "Item2"
Combo1.AddItem "Item3"
Combo1.AddItem "Item4"
End Sub
Horizontal and Vertical Scroll Bars
Horizontal and vertical scroll bars are widely used in Windows applications. Scroll bars provide
an intuitive way to move through a list of information and make great input devices.
Scroll Bar Properties:
LargeChange -Increment added to or subtracted from the scroll bar Value property when
the bar area is clicked.
Max -The value of the horizontal scroll bar at the far right and the value of the vertical
scroll bar at the bottom.Can range from -32,768 to 32,767.
Min -The other extreme value - the horizontal scroll bar at the left and the vertical scroll
bar at the top. Can range from - 32,768 to 32,767.
SmallChange -The increment added to or subtracted from the scroll bar Value property
when either of the scroll arrows is clicked.
Value -The current position of the scroll box (thumb) within the scroll bar.
Frames
Frames provide a way of grouping related controls on a form. These are containers; they can be
used to display information or containers for option buttons. Option buttons within a frame work
as a group, independently of option buttons in other frames or in the form. The diagram below
illustrates a simple Frame being used to display information:
The CheckBox
Check boxes provide a way to make choices from a list of potential candidates. Some, all, or
none of the choices in a group may be selected. The Check Box control lets the user selects or
unselects an option. When the Check Box is checked, its value is set to 1 and when it is
unchecked, the value is set to 0. You can include the statements Check1.Value=1 to mark the
Check Box and Check1.Value=0 to unmark the Check Box, as well as use them to initiate
certain actions. The program in Example will show which items are selected in a message box.
Private Sub Cmd_OK_Click()
If Check1.Value = 1 And Check2.Value = 0 And Check3.Value = 0 Then
MsgBox "Apple is selected"
ElseIf Check2.Value = 1 And Check1.Value = 0 And Check3.Value = 0 Then
MsgBox "Orange is selected"
ElseIf Check3.Value = 1 And Check1.Value = 0 And Check2.Value = 0 Then
MsgBox "Orange is selected"
ElseIf Check2.Value = 1 And Check1.Value = 1 And Check3.Value = 0 Then
MsgBox "Apple and Orange are selected"
ElseIf Check3.Value = 1 And Check1.Value = 1 And Check2.Value = 0 Then
MsgBox "Apple and Pear are selected"
ElseIf Check2.Value = 1 And Check3.Value = 1 And Check1.Value = 0 Then
MsgBox "Orange and Pear are selected"
Else
MsgBox "All are selected"
End If
End Sub
The OptionButton
The OptionButton control also lets the user selects one of the choices. However, two or more
Option buttons must work together because as one of the option buttons is selected, the other
Option button will be unselected. In fact, only one Option Box can be selected at one time.
When an option box is selected, its value is set to “True” and when it is unselected; its value is
set to “False”.
Private Sub cmd_SetColor_Click()
If Option1.Value = True Then
Form1.BackColor = vbRed
ElseIf Option2.Value = True Then
Form1.BackColor = vbBlue
Else
Form1.BackColor = vbGreen
End If
End Sub
The Shape Control
The shape tool can create circles, ovals, squares, rectangles, and rounded squares and
rectangles. Colors can be used and various fill patterns are available.
Shape Tool Properties:
BackColor - Determines the background color of the shape (only used when FillStyle not
Solid).
BackStyle - Determines whether the background is transparent or opaque.
BorderColor- Determines the color of the shapes outline.
BorderStyle -Determines the style o the shapes outline. The border can be transparent,
solid, dashed, dotted, and combinations.
BorderWidth - Determines the width of the shape border line.
fillColor - Defines the interior color of the shape.
FillStyle - Determines the interior pattern of a shape. Some choices are: solid,
transparent, cross, etc.
Shape - Determines whether the shape is a square, rectangle, circle, or some other
choice.
In the following example, the shape control is placed in the form together with six
OptionButtons. To determine the shape of the shape control, we use the shape property. The
property values of the shape control are 0, 1, and 2,3,4,5 which will make it appear as a
rectangle, a square, an oval shape, a circle, a rounded rectangle and a rounded square
respectively.
Private SubMyOption_Click(Index As Integer)
If Index = 0 Then
MyShape.Shape = 0
ElseIf Index = 1 Then
MyShape.Shape = 1
ElseIf Index = 2 Then
MyShape.Shape = 2
ElseIf Index = 3 Then
MyShape.Shape = 3
ElseIf Index = 4 Then
MyShape.Shape = 4
ElseIf Index = 5 Then
MyShape.Shape = 5
End If
End Sub
The DriveListBox
The DriveListBox is for displaying a list of drives available in your computer. When you place
this control into the form and run the program, you will be able to select different drives from
your computer as shown below.
The DirListBox
The DirListBox means the Directory List Box. It is for displaying a list of directories or folders in
a selected drive. When you place this control into the form and run the program, you will be able
to select different directories from a selected drive in your computer as shown below.
The FileListBox
You can coordinate the Drive List Box, the Directory List Box and the File List Box to search for
the files you want. You can change the Pattern property value to view only specific type files in
the current directory. The default Pattern property value is *.*.
The Line Control
Like the shape control, the line control is a graphical control. Line is use it to display horizontal,
vertical, or diagonal lines in a form.We can use these controls at design time as a design
element or at runtime to alter the original line you drew. It can also change a line at runtime by
changing its X1, X2, Y1, and Y2 properties.
Line Tool Properties:
BorderColor Determines the line color.
BorderStyle Determines the line shape. Lines can be transparent, solid, dashed, dotted,
and combinations.
BorderWidth Determines line width.
The Timer Control
You use a timer control when you want to execute code at specific intervals. Many times,
especially in using graphics, we want to repeat certain operations at regular intervals. The timer
tool allows such repetition. The timer tool does not appear on the form while the application is
running.
Timer Properties:
Enabled - Used to turn the timer on and off. When on, it continues to operate until the
Enabled property is set to False.
Interval - Number of milliseconds between each invocation of the Timer Event. To stop
the timer set Interval=0 and To start the timer set with Interval=10.