Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the...

76
W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university 1 Lecture1 1- Introduction to Programming and Visual Basic Before plunging into learning Visual Basic, we will review the fundamentals of computer hardware and software, and then become familiar with the Visual Basic programming environment. 1.1Computer Systems Hardware refers to a computer‘s physical components. Computer is not an individual device, but rather a system of devices. Like the instruments in a symphony orchestra, each device plays its own part. A typical computer system consists of: 1. The central processing unit (CPU) 2. Main memory 3. Secondary storage devices 4. Input devices 5. Output devices Fig. (1-1) the organization of a computer system. Software refers to the programs that run on a computer. There are two general categories of software: Operating systems and application software. An operating

Transcript of Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the...

Page 1: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

1

Lecture1

1- Introduction to Programming and Visual Basic

Before plunging into learning Visual Basic, we will review the fundamentals of computer

hardware and software, and then become familiar with the Visual Basic programming

environment.

1.1Computer Systems

Hardware refers to a computer‘s physical components. Computer is not an individual

device, but rather a system of devices. Like the instruments in a symphony orchestra, each

device plays its own part.

A typical computer system consists of:

1. The central processing unit (CPU)

2. Main memory

3. Secondary storage devices

4. Input devices

5. Output devices

Fig. (1-1) the organization of a computer system.

Software refers to the programs that run on a computer. There are two general

categories of software: Operating systems and application software. An operating

Page 2: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

2

system or OS is a set of programs that manages the computer‘s hardware devices and

controls their processes.

Examples: Windows, Mac OS, and Linux are all operating systems.

Application software refers to programs that make the computer useful to

the user. These programs, which are generally called applications, solve

specific problems or perform.

Examples: Word processing, spreadsheet, and database packages

Note: As you work through this Semester, you will develop application software using

Visual Basic.

1.2Programs and Programming Languages

A program is a set of instructions a computer follows in order to solve a problem

or perform a task. For example, suppose we want the computer to calculate someone‘s

gross pay—a Wage Calculator application. A programming language is a special

language used to write computer programs.

The instructions in Fig.(1-2) are called an algorithm. An algorithm is a set of well-

defined steps for performing a task or solving a problem. Notice these steps are

sequentially ordered. Step 1 should be performed before Step 2, and so on. It is important

that these instructions are performed in their proper sequence.

.

Fig.1-2 Program steps—Wage Calculator application

4- How much do you get paid per hour?

5- enter an hourly pay rate.

6- the user enters a number, store it in memory

1- How many hours did you work?

2- Enter the number of hours worked

3- the user enters a number, store it in memory.

7-Multiply the two numbers and store the result in

memory as the gross pay

8- Display a message on the screen that

shows the gross pay

Page 3: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

3

It is helpful to think of a running computer program as a combination of states and

transitions. Each state is represented by a snapshot (like a picture) of the computer‘s

memory.

Suppose:

number of hours worked by the user is 20 hour... stored in memory, (step3).

hourly pay rate entered by the user is 25 $/hour ... stored in memory, (step6).

The memory snapshot produced by Step 7 represents the final program state, see Fig. (1-

3).

Fig.(1-3) Memory snapshot taken when the program starts:

In order for a computer to perform instructions such as the wage calculator

algorithm, the steps must be converted to a format the computer can process. As

mentioned earlier, a program is stored in memory as a series of binary numbers. These

numbers are known as machine language instructions. The CPU processes only

instructions written in machine language. Our Wage Calculator application might look

like the following at the moment when it is executed by the computer:

Page 4: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

4

10101101110101000111100001101110100011110001110011010101110 etc.

The CPU interprets these binary or machine language numbers as commands. As

you might imagine, the process of encoding an algorithm in machine language is tedious

and difficult. Programming languages, which use words instead of numbers, were

invented to ease this task.

Different software companies produced different of high-level languages but only

a few have achieved broad acceptance, for example (QBASIC, FORTAN and Pascal).

However, people prefer to use Visual Basic (Microsoft Windows Programming

language).

Programmers can write their applications in programming language statements, and

then use special software called a compiler to convert the program into machine

language. Names of some popular recent programming languages are shown in Table 1-1.

This list is only a small sample—there are thousands of programming languages.

Table (1-1) some popular recent programming languages

Language Description

Visual

Basic, C#

Popular programming languages for building Windows and Web

applications.

C, C++ Powerful advanced programming languages that emphasize

flexibility and fast running times. C++ is also object-oriented.

Java Flexible and powerful programming language that runs on many

different computer systems. Often used to teach object-oriented

programming.

Python Simple, yet powerful programming language used for graphics and

small applications

PHP Programming language used for creating interactive Web sites.

JavaScript Scripting language used in Web applications that provides rich user

interfaces for Web browsers.

All programming languages, including Visual Basic, have certain elements in

common. Let‘s look at the major programming language elements that you will work

with when writing a program.

Page 5: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

5

1.3 What is visual basic?

Visual Basic is an example of a graphical-based language, which evolved from the

earlier DOS version called BASIC. A graphical-based language allows the user to work

directly with graphics. Visual Basic is derived from the ―visual‖ term refers to the

method used to create the graphical user interface (GUI). The ―Basic‖ term refers to the

BASIC (Beginners All-Purpose Symbolic Instruction Code) language, a language used

by more programmers.

1.4 Why we choose visual basic?

In the following points we can summarize some important points about visual basic

language:

1- It is a very easy programming language to learn ,Simply drag and drop prebuilt

objects into place on screen without having to learn an additional software package

2- Beginners can create useful applications by professionals to accomplish anything

that can be accomplished using any other windows programming language.

3- The language not only allows programmers to create simple GUI (graphical user

interface) applications, but can also develop complex applications.

4- It uses integrated development environment (IDE) which is easier for the user to

minimize code writing.

5- All visual programs follow the same concepts; therefore the user will become

more familiar with visual approach for other visual languages.

6- It provides Input box and Output box as an interactive windows with user.

7- It is able to connect to Internet, and to call Explorer.

8- With VB 6, you can create any program depending on your objective. For example

you can create educational programs to teach business, economics, engineering,

computer science, accountancy, financial management, information system and

more to make teaching more effective and interesting.

1.5 Visual Basic 6.0

Visual Basic has evolved from the original BASIC language and now contains

several hundred statements, functions, and keywords, many of which relate directly to the

windows GUI, some identified new features of Visual Basic 6.0:

Faster compiler.

New ActiveX data control object.

Allows database integration with wide variety of applications.

New data report designer.

New Package & Deployment Wizard.

Page 6: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

6

Additional internet capabilities.

Checkpoints

Explain why computers have both main memory and secondary storage.

What are the two general categories of software?

What is the binary system?

Give your example of an application program, and which machine language will you

choose to write a program?

What do you know about Visual basic programming language?

Practical part

1- Review of:

Computer constitutions

Computer systems (hardware and software)

2- Explanation how to start using Visual Basic language program.

Page 7: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

7

Lecture2

2- Structure of a Visual Basic Application

To run Visual Basic program select, Start> Programs > Microsoft Visual Studio 6.0>

Microsoft Visual Basic 6.0 as shown in Fig.(2-1). When Visual Basic is loaded, the New

Project dialog shown in Fig. (2-2) is displayed.

Fig.(2-1) Computer screen Fig.(2-2) New Project dialog.

The New Project dialog allows the programmer to choose what type of Visual Basic

program to create. Standard EXE, which is highlighted by default, allows the programmer to

create a standard executable. Each type listed in Fig.(2-2) describes a group of related files

called a Project.

2.1 Project (VBP)

Project is a program designed to user application that may be simple (like

calculator program) or complex (like word program). The project types listed in Fig.(2-3)

are the ―Visual‖ in Visual Basic, because they contain predefined features for designing

Windows programs. The project is a collection of files that makes the user program. They

may consist of form, modules, active x controls.

The new project dialog contains three tabs :

New: creating new project.

Existing: opening an existing project.

Recent: opening a project that has been previously loaded into the IDE.

Page 8: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

8

2.2 Elements of Integrated Development Environmental (IDE).

Figure (2-3) shows The IDE after Standard EXE is selected. The top of the IDE

window (the title bar) displays ―Project1-Microsoft Visual Basic [design]‖.The

environment consists of various windows when Visual Basic is started (by default):

Fig. (2-3) visual basic windows

1- Main Window: as shown in Fig. (2-4) consists of the title bar, menu bar, and

toolbar:

The title bar indicates the project name, the current Visual Basic operating

mode, and the current form.

The menu bar has drop-down menus from which you control the operation

of the Visual Basic environment, which Contains a standard command and

specific command like (File, Edit, View, Project, Format, Debug, Run, etc.)

The toolbar has buttons that provide shortcuts to some of the menu options

and Contains several icons that provide quick access to commonly used

features.

Main

window

Toolbox

Controls

Form

window Properties

Window

Form

Layout

Window

Project

Window

Page 9: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

9

The main window also shows the location of the current form relative to the

upper left corner of the screen (measured in twips) and the width and length of the

current form.

Fig. (2-4) Main Window

2- Form1 (Form)window :contains a form named Form1, which is where the

program‘s Graphical User Interface (GUI) will be displayed as shown in Fig. (2-

5).

Fig. (2-5) Form window

3- Toolbox Controls: Contains a collection of tools that are needed for project

design as shown in Fig.(2-6). To show the toolbox press View> toolbox icon. The

user can place the tool on form, and then work with the tool. To place the tool on

form: click on tool>draw tool to form > the tool appears on form or double click

on tool then the tool appears on form. Table (2-1) summarizes the toolbox

controls.

Page 10: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

10

Fig. (2-6) Toolbox Window.

Table (2-1): Toolbox controls summary.

Control Description

Pointer Used to interact with controls on the form(resize them, move

them, etc.). The pointer is not a control

PictureBox A control that display images or print the result.

Label A control that displays uneditable text to the user.

TextBox A control for accepting user input. Textbox can also display text.

Frame A control for grouping other controls

CommandButton A control that represents a button. The user presses or clicks to

initiate an action.

CheckBox A control that provides the user with a toggle choice (checked or

unchecked)

OptionButton Option buttons are used in groups where only one at a time can

be true

ListBox A control that provides a list of items.

ComboBox A control that provides a short list of items.

HscrollBar A horizontal scrollbar.

VscrollBar A vertical scrollbar.

Shape A control for drawing circles, rectangles, squares or ellipse

Line A control for drawing line.

DrivelistBox A control accessing the system disk drivers. A control accessing

directories on a system

DirlistBox A control accessing directories on a system

Filelistbox A control accessing file in a directory .

Image A control for displaying images. The images control does not

provide as many capabilities as a picturebox.

Page 11: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

11

OLE A control for interacting with other window applications.

Timer A control that performs a task at programmer specified intervals.

A timer is not visible to the user.

4- Properties Window: The properties window displays the properties for a form or

control as shown in Fig.(2-7). Properties are attributes such as size, position, etc.

like a form; each control type has its own set of properties. Some properties, like

width and height, such as, are common to both forms and controls, while other

properties are unique to form or control. Controls often differ in the number and

type of properties. Properties are listed either alphabetically (by selecting the

alphabetic tab) or categorically (by selecting the categorized tab). The most

important properties of the objects in general are listed in the following table. To

show the properties window press View> properties window icon. Table (2-2)

explain objective of the properties window.

Fig.(2-7) Properties Window

Table (2-2) explanation of the properties window.

Properties

name

Objective

Name Used to represent name of object in code.

Caption Name appears on object.

Back color Background color for object.

Fore color Color of text written on object.

Font Font style type and size

Visible The tool is visible or invisible.

Enable The tool enable or disable

Page 12: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

12

Height Length of object

Width Width of object

Top Coordinates of top of object on screen

Left Coordinates of left of object on screen

Text Allows inputting and editing text in object.

5- Form Layout Window: The Form Layout window specifies a form‘s position on

the screen at runtime as shown in Fig.(2-8). The Form Layout window consists of

an image representing the screen and the form‘s relative position on the screen.

With the mouse pointer positioned over the form image, drag the form to a new

location.

Fig.(2-8) Form Layout Window

6- Project Window: displays a list of all forms and modules making up your

application see Fig.(2-9). You can also obtain a view of the Form or Code

windows (window containing the actual Basic coding) from the Project window.

Fig.(2-9) Project Window

Note:

There are two ways to place controls on a form:

Page 13: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

13

1. Double-click the tool in the toolbox and it is created with a default size on the

form. You can then move it or resize it.

2. Click the tool in the toolbox, and then move the mouse pointer to the form

window. The cursor changes to a crosshair. Place the crosshair at the upper

left corner of where you want the control to be, press the left mouse button

and hold it down while dragging the cursor toward the lower right corner.

When you release the mouse button, the control is drawn.

To move a control you have drawn, click the object in the form window and drag

it to the new location. Release the mouse button.

To resize a control, click the object so that it is select and sizing handles appear.

Use these handles to resize the object, as shown in Fig.(2-10).

Fig.(2-10).

2.3 Code Editor Window:

Code Editor Window is used to write a VB code for an application. For each form

there is a separate code editor window. It is displayed when user clicks on form or object

in form. As shown in Fig. (2-11).

Fig.(2-11) Code Editor Window

2.3.1 Sub Procedures:

Page 14: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

14

A Sub Procedure is a block of code that is executed in response to an event.

By breaking the code in a module into Sub procedures, it becomes much easier to

find or modify the code in your application. The syntax for a Sub procedure is:

Private Sub procedurename (arguments)

Statements

End Sub

2.3.2 Events:

Events are like electrical switches. The electrical switches are of many types,

so are the events. The form and controls support events (generation, interaction

with mouse and keyboard). The most important events in Visual Basic are

described in the following table.

Table (2-3) description of the most important events.

Event Action taken when It provide the

following integers

Click Single click on object.

DbClick Double click on object.

Mouse move Mouse pointer move object. Button ,shift ,X,Y

Key press Pressing a key of the key board. Key Ascii

DragDrop Move object to another place. Source, X, Y

load Loading the object

Checkpoints

1-Define the following parameters:

(Toolbar, ToolBox, Form window,form layout,project window,properties window,code editor

window,Events)

2- Explain the advantage of the Visual Basic program

Page 15: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

15

Practical part

Example 2-1: Design a form such that: in event load, when project runs, the form

backcolor property changed (chose any color).

Code:

Private Sub Form_Load()

Form1.BackColor = QBColor(12)

End Sub

Example 2-2: Design a form such that: in event click on form, when project runs, the title of the

form changed to applied science.

Exercises:

2-1 Design a standard project has three forms with backcolors red, blue and green.

2-2 design a standard project that has one form change the name from form1 to

"students"

2-3 Create a standard project with one form the name of the project "market seals" and

the name of the form "stock markets" and save project on desktop with name

marketing .exe

2-4 Design a standard project with four forms when running project all forms appear

on screen Note :use this code in form1 (form1.show, form2.show, form3.show,

form4.show)

2-5 Design a form contains label " F.O.W.R.E" in size 14.

Page 16: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

16

Lecture3

2.4 Steps in Developing Application:

Before starting to build an application we need to understand definitions of some

terms in visual basic and their relationship between each other, see Fig.(2-12 ):

Fig. (2-12) some terms in VB schematically.

Events: The form and controls support events (generation, interaction with mouse

and keyboard)

Properties

(which can be set at the design time by selecting the Properties Window) ,For

example, a TextBox accepts properties such as Enabled, Font, MultiLine,

Text, Visible, Width, etc.

Certain properties cannot be set at design time. For example, the CurrentX

and CurrentY properties of a Form cannot be set at the design time.

Method is an action that can be performed on objects. . For example, a form has a

Hide method that makes it invisible to the user.

Page 17: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

17

Procedures are often written to respond to a specific event. Types of procedures

include Sub-procedures, which consist of a sequence of statements; and

Functions, which return a value.

Code : The codes are of two categories:

Declaration is written before any procedure in the code.

Statements The user selects the required event then code statements are

written inside these event procedures.

The user interface: is composed of the screens you design by using Visual

Basic's forms and controls.

The processing of information: is done by the set of statements written to add the

functionality to the object.

The Storage for Information: is generally any backend Database, which is

connected to frontend by any of the standard Data Control or through Designers.

There are three primary steps involved in building a Visual Basic application:

1- Draw the user interface

2- Assign properties to controls

3- Attach code to control

Select type of project New or Exciting. A form automatically

appears in the form design.( User can add other forms to the

project : select project menu>add form).

To add objects (controls) to the form use the ToolBox.

Set the properties for the objects through properties window.

Write code. The Visual Basic Code consists of statements, and

Declarations (The code for an application can be written on the Code

Editor window).

Page 18: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

18

To see how this is done, use the steps in the following procedures to create a

simple application for the following example:

Example 2-3: Design a form with one text box and two Commands button. Write a code

so when run project and click on command1 (O.k.) replace the word (Welcome) in text

box, and when click on Command2 (Close) terminate the program and return back to the

form interface.

Solution:

Creating the Interface:

The first step in building a Visual Basic application is to create the forms that will

be the basis for your application‘s interface. Then you draw the objects that make up the

interface on the forms you create.

1- Adding a text box to the form. Double-click the toolbox‘s textbox to create a text

box with sizing handles in the center of the form.

2- Adding a Command Button1 to the form. Click on button and draw button1 to

form then the button appears on form.

3- Repeat step 2 to add a Command Button2 to the form.

Page 19: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

19

Setting Properties:

The next step is to set properties for the objects. The properties window provides

an easy way to set properties for all objects on a form. For the Example 1, you‘ll need to

change three property setting. Use the default setting for all other properties.

Note:

1- The Caption property determines what is displayed in the form‘s title bar

or what text the controls displays on a form.

2- The TextBox‘s Text Property determines what text (if any) the TextBox

displays.

3- The Name property identifies a form or control. It‘s necessary only for

writing code.

Page 20: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

20

Object Property Setting

Form1 Name Form1

Caption Example1

Font Bold and size 12

Command Button1 Name Command1

Caption o.k.

Font Bold and size 12

Command Button2 Name Command 2

Caption close

Font Bold and size 12

TextBox Name Text1

Text Empty

Writing Code:

The code editor window is where you write Visual Basic code for your application.

Code consists of language statements, constants, and declarations. To open the code

window, double-click the form or control for which you choose to write code, or from the

Project Explorer window, select the name of a form and choose the View code button.

In the Object list box, select the name of an object in the active form. Or

double click of an object.

In the procedure list box, select the name of an event for the selected

object. The Click procedure is the default procedure for a command

button and the Load is default procedure for a form.

An event procedure for a control combines the control‘s actual name

(specified in the name property), an underscore ( _ ), and the event name.

For example (Command1_click).

Type the code between the Sub and the End Sub statements.

Choose the command1 and type the following code:

Private Sub Command1_click ( )

Text1.text=”Welcome”

Page 21: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

21

End Sub

Choose the command2 and type the following code:

Private Sub Command2_click ( )

End

End Sub

Note: we will use the word design instead of interface creating and setting of properties

The statement END used to close the program runtime.

Running the Application:

To run the application, choose start from the run menu, or click the start button on

the toolbar, or F5 Click the command button (O.k.) and see the ―Welcome‖

displayed in the text box. Click the command button (close) the end the program and

return to the form window.

Example 2-4: Design a form with one textbox, set the text properties so that this massage

appears when project runs (welcome to visual basic world).

Solution: 1- Design

Object Property Setting

Form1 Name Form1

Caption Example

2-4

font Bold and

size 14

Fillcolor Black

TextBox Name Text1

Text Empty

Backcolor Gray

Forecolor Blue

Page 22: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

22

2- Code writing

Private Sub Form_Load()

Text1.Text = "welcome to visual basic world"

End Sub

3- Running the application

Practical part

Example 2-5: Design a form shown in figure below, with three text boxes and one

Command Button. Write code in the Command1 (Execute). So when run project enter the

Student Name in TextBox (Txt1) and the Father Name in TextBox (Txt2). When click on

Command1 (Execute) replace the Full Name in the TextBox(Txt3).

Solution:

Design :

1. Adding a Label to the form1. Double-click the Label‘s Label to create a Label

with sizing handles in the center of the form1.

2. Repeat step 1 to add Label2 and Label3.

3. Adding a TextBox to the form1. Double-click the toolbox‘s textbox to create a

text box with sizing handles in the center of the form1.

4. Repeat step 3 to add Text2 and Text3.

5. Adding a Command Button1 to the form. Click on button and draw Button to

form then the Button1 appears on form1.

Page 23: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

23

Object Property Setting

Form1 Name Form1

Caption Example2-5

Font Bold and size

12

Command Button1 Name Command1

Caption Execute

Font Bold and size

12

TextBox1 Name Text1

Text Empty

TextBox2 Name Text2

Text Empty

TextBox3 Name Text3

Text Empty

Label1 Name Label1

Caption Student name

Font Bold and size

12

Label2 Name Label1

Caption Student name

Font Bold and size

12

Label3 Name Label1

Page 24: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

24

Caption Father name

Font Bold and size

12

Writing Code:

Choose the Form1 and type the following code:

Private Sub Form1_load ( )

Txt3.width =Form1.width-100

End Sub

Choose the command1 and type the following code:

Private Sub Command1_click ( )

Txt3.text=tex1.text+ “ “+txt2.text

End Sub

Running the Application:

To run the application, choose start from the run menu, or click the start button on

the toolbar , or F5 Click the command button1 (Execute) and see the Full Name

displayed in the TextBox3.

Saving a Project:

Choosing save project from the file menu. Visual Basic will prompt you separately

to save the form and then the project.

Example 2-6: Design a form to appear your name and department in textbox, when click

on command button "name" and "department" respectively so that you can clear these

informations when click on command "clear" and stop project when click on

command "exit".

Solution:

Page 25: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

25

1- design

2- code writing

Private Sub Command1_Click()

Text1.text="Muna"

End Sub

Private Sub Command2_Click()

Text1.text="Engineer"

End Sub

Private Sub Command3_Click()

Text1.text=" "

End Sub

Private Sub Command4_Click()

end

End Sub

Running the application

Page 26: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

26

Lecture 4

3- Fundamentals of programming in Visual Basic

3-1 Visual basic statements

In visual basic program (code) there are four basic parts, i.e. it is contains the

following statements:

1- Declaration of variables and constants

2- Inputting variables

3- Operators for variables

4- Outputting variables.

1- Declaration of a variable and constants: the declaration means defining the data

type (variable or constant).

Variables: A variable is a space in memory filled with data (value, character, time or

date).

Notes:

Variable name must start with character (not number or function) and maximum

length 256 character, and does not contain point or symbol. The names of

controls, forms, and modules must not exceed 40 characters.

Variable name must not repeat for other values.

They can‘t be the same as restricted keywords (a restricted keyword is a word

that Visual Basic uses as part of its language. This includes predefined

statements such as ―If and Loop‖, functions such as ―Len and Abs‖, and

operators such as ―Or and Mod‖).

The variable has to be declared. Variable type is defined by its content .The

content may be data as numeric or character or string or Boolean or date, or any

type of data (called variant), these types declared as:

Dim variable name as type

Or

Global variable name as type

The Dim declaration written in general part of the form or in any place in form or

sub procedure which used for one form. While Global declaration used for all forms.

Page 27: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

27

The types of variables that are allowed in visual basic are stated in the table below:

Table (3-1) variables of visual basic.

Type bytes Value range Suffix Declaration

Integer 2 -32768<x<32768 % Dim x as integer or Dim x %

Long

(Integer)

4 -2.1 e+009<x<2.1 e+009 & Dim x as long or Dim x &

Single 4 1.4e-045 <|x|<3.4e+038 ! Dim x as single or Dim x !

Double 8 4.9e-324<x<1.79e+308 # Dim x as double or Dim x #

String 1 65535 characters $ Dim x as string or Dim x $

Boolean 2 True or false None Dim x as Boolean

Date 8 Computer time and date

Jan 100<x< 31 Dec 9999

None Dim x as date

Currency 8 -9e+014 <x< 9e+014 @ Dim x as Currency or Dim x @

Variant: A variable of type variant can be assigned numbers, Strings and several other

types of data. A variable of type variant requires 16 bytes of memory and can hold any

type of data.

Examples:

Dim X As Integer

Dim Balance As Currency

Dim Y As Long

Dim A AS Double, B As Double

Dim Month As Date

Dim Max As Single

Dim Name As String

Error examples:

Dim x As string : Dim A, B, C, X (Repeat the variable name at the same

time in two Dim tatement)

Dim 1st As date (first character is number)

Dim (Ad#1) As string (symbol)

Dim MyName.is As string (point)

Page 28: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

28

Dim Num one As long (space)

Constants: It is a space in memory filled with fixed value that will not be changed.

Constant may be declared as:

Const constant name = value

There are two sources for constants:

System-defined constants are provided by applications and controls. Visual Basic

constants are listed in the Visual Basic (VB).

User-defined constants are declared using the Const statement. It is a space in

memory filled with fixed value that will not be changed.

For example:

Const X=3.14156 Constant for procedure

Private Const X=3.14156 Constant for form and all procedure

Public Const X=3.14156 Constant for all forms

2- Inputting variables

There are two methods to input variable X as stated in the following:

Method of input For all type of variable

In text tool X=textno.text

In inputbox X=inputbox("prompt","title")

Note: To enter many variables we usually use the second method with loop, will

explained later.

3- Operators for variables the operators that are used for variable are described in the

following table:

Table (3-2) operators for variables .

Arithmetic operators

+ addition

- subtraction

* multiplication

/ division

mod Modulus –rest of division

^ exponent

= equal

< Less than

Page 29: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

29

Relational operators <= Less or equal

> Greater than

>= Greater or equal

< > Not equal

Examples:

Assignment Statement :There are many statements ways to fill a variable as follows:

Variable = expression

Expression may include variables, operations and functions as follows:

1- Numerical variable i=3

2- Mathematical relation x=a/b

3- Characters variable (string) t="abc"

4- Boolean variable (logical) p=true

Example 3-1: write a program to add two integer numbers after putting a suitable

design.

Solution:

1- Design

Page 30: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

30

2- Code writing :

Command Button1(calculate ):

Dim x, y as integer

Private Sub Command1_click

X=val(text1.text)

Y=val(text2.text)

Text3.text= X+Y

End Sub

3- Running the application.

Page 31: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

31

Practical part

Example 3-2: Construct a simple calculator ( + , - , x , / ) using Visual Basic 6.

Solution:

1- Design :

Page 32: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

32

2- Code writing :

Dim x, y as integer

Command Button1:

Private Sub Command1_click

X=val(text1.text)

Y=val(text2.text)

Text3.text= X+Y

End Sub

Command Button2:

Private Sub Command1_click

X=val(text1.text)

Y=val(text2.text)

Text3.text= X-Y

End Sub

Command Button3:

Private Sub Command1_click

X=val(text1.text)

Y=val(text2.text)

Text3.text= X*Y

End Sub

3- Running the application.

Exercises:

3-1 Design a program to find value of z from the following equation:

.

3-2 Write a Program to compute the area of triangle with design.

Page 33: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

33

Lecture 5

Visual Basic Functions:

Visual Basic provides the user with many functions to be used with a variable to

perform certain operations or type conversion. The most common functions for (numeric

or string) variable X are stated in table (6).

Table (3-3) visual basic function.

Function Description

Numerical Function

X= RND Create random number value between 0 and 1

Y=ABS(X) Absolute of X, |X|

Y=SQR(X) Square root of X , √𝑋

Y=SGN(X) (-1 or 0 or 1) for (X<0 or X=0 or X>0)

Y=EXP(X) 𝒆x

Y=LOG(X) Natural logarithms, ln𝑋

Y=LOG(X) / LOG(10) Log𝑋

Y=sin (𝑋)

Y=cos (𝑋)

Y=tan (𝑋)

Trigonometric functions

Y=ATN(X) Is arc= tan−1

(𝑋) (Where X angle in radian).

Y=INT(X) Integer of X

Y= FIX(X) Take the integer part

Function of String Variable

Y=Len(x) Number of characters of Variable

Y=LCase (x) Change to small letters

Y=UCase (x) Change to capital letters

Y=Left (X,L) Take L character from left

Y=Right (X,L) Take L character from right

Y=Mid (X,S,L) Take only characters between S and R

Page 34: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

34

Converting Data Types:

Visual Basic provides several conversion functions can used to convert values into

a specific data type. The following table describes the convert function:

Table(3-4) describes the convert function.

Function Description

CDbl The function CDbl converts, integer, long integer, and single- precision

numbers to double-precision numbers. If x is any number, then the

value of CDbl(x) is the double-precision number determined by x.

CInt The function CInt converts long integer, single-precision, and double

precision numbers to integer numbers. If x is any number, the value of

CInt(x) is the (possibly rounded) integer constant that x determines.

CLng The function CLng converts integer, single precision and double-

precision numbers to long integer numbers. If x is any number, the

value of CLng(x) is the (possibly rounded) long integer that x

determines.

CSng The function CSng converts integer, long integer, and double-precision

numbers to single-precision numbers. If x is any number, the value of

CSng(x) is the single-precision number that x determines.

CStr The function CStr converts integer, long integer, single-precision,

double-precision, and variant numbers to strings. If x is any number, the

value of CStr(x) is the string determined by x. unlike the Str function,

CStr does not place a space in front of positive numbers.[variant]

Str The Str function converts numbers to strings. The value of the function

Str(n) is the string consisting of the number n in the form normally

displayed by a print statement.

Val The Val function is used to convert string to double-precision numbers.

Note: The following function

values for different X are

given for comparison.

X= 10.999 - 10.999 10.123 -10.123

FIX(X) 10 -10 10 -10

INT(X) 10 -11 10 -11

CINT(X) 11 -11 10 -10

Page 35: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

35

Examples:

4- Outputting variables:

There are methods to output variable x as stated in the following table:

Table (3-5) outputting variables.

Method of output For all type of variable

On form Print x

Note: in load event we must use the statement:

(form1.show)

to text tool Textno.text =X

to label tool Labelno.caption=x

By message box msgbox (x)

Or msgbox ("remark"& x)

The instruction print could be very helpful to display data and used as follows:

Functions Output

A=Lcase ("My Name Is") A= my name is

A=Ucase ("My Name Is") A=MY NAME IS

A=" My Name Is": B=Left (A,7) B=My Name

C=Right(A,7) C=Name Is

D= Mid (A,3,5) D=Name

E=Mid(A,3) E=Name Is

Int(2.5) 2

Int(-2.5) -3

Fix(2.5) 2

Fix(-2.5) -2

Code Description Example

Page 36: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

36

Exercises :

print To leave one line and

print on next

Print "a", "b", "c" Use (,) to print a distance

between outputs

A b c

Print "a"; "b"; "c" Use (;) to print the

outputs adjacent

abc

Print "a","b";

Print "c"

Print a, b then print c on

the same line

abc

Page 37: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

37

Practical part

Example 3-3: write a program to compute the functions: sine, cosine, integer value, square,

absolute value.

Solution:

1- Design :

2- Code writing

Dim x, y As Single

Private Sub command1_click()

x = Val(Text1.Text)

y = Abs(x)

Text1.Text = CStr(y)

End Sub

Private Sub Command2_Click()

x = Val(Text1.Text)

y = Sqr(x)

Text1.Text = CStr(y)

End Sub

Private Sub Command3_Click()

x = Val(Text1.Text)

y = Int(x)

Page 38: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

38

Text1.Text = CStr(y)

End Sub

Private Sub Command4_Click()

x = Val(Text1.Text)

y = Sin(x * 3.14159 / 180)

Text1.Text = CStr(y)

End Sub

Private Sub Command5_Click()

x = Val(Text1.Text)

y = Cos(x * 3.14159 / 180)

Text1.Text = CStr(y)

End Sub

3- Running the application

Example 3-4: Create a Visual Basic project to solve for the roots of the quadratic

equation aX2+bX+c = 0 , using quadratic formula X1,2=

. Design the

program so that the values of a, b, and c are entered into separate (labeled) text boxes and

display 𝑋1 , 𝑋2 in in separate (labeled) text boxes?

Solution:

1- Design

Page 39: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

39

2- Code writing :

Dim a , b , c , X1 , X2 as integer

Private Sub Cmd1_ click ( )

a= Val (Txt1.text)

b= Val (Txt2.text)

c= Val (Txt3.text)

X1=Cdbl (- b + Sqr (b ^ 2 – 4 * a * c)) / (2 * a)

X2= Cdbl (- b – Sqr (b ^ 2 – 4 * a * c)) / ( 2 * a)

Txt4.text = CStr (X1)

Txt5.text = CStr (X2)

End Sub

3- Running the application .

Page 40: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

40

Exercises:

3-3 Write a program to find value of y from the following equation:

( ) ( ) , then show the result on form .

3-4 Write a program to enter any text and compute its length. Put suitable design.

3-5 Write a program to enter a real number then find its square after putting suitable

design.

Page 41: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

41

Lecture 6

3-2 Properties Method (Extension)

Before writing an event procedure for the control to response to a user's input, you

have to set certain properties for the control to determine its appearance and how it will

work with the event procedure. You can set the properties of the controls in the properties

window at design time or at runtime. You can also change the properties of the object at

runtime to give special effects such as change of color, shape, animation effect and so on.

The properties that are discussed below are design-time properties.

Table (3-6)

properties Description

Backcolor Determines the background color of an object.

Caption Holds the text that is to appear as the caption for a form,

command button or label

Text Holds the text that is to appear as the Text for a TextBox

Enable Determines whether or not a form or control responds to events.

The Enabled property of a control is set to (True or False)

FontBold Determines whether the characters printed on an object appear in

bold or normal type. The FontBold property is set to (True or

False)

FontItalic Determines whether the characters printed on an object appear in

italic or upright type. The FontItalic property is set to (True or

False)

FontUnderline Determines whether the characters printed on an object appear

with an underline. The FontUnderline property is set to (True or

False)

FontSize Determines the size, in prints, of characters printed on an object

appear with an underline. Default font size is usually 8 point.

Font Determines what type face is used when characters are printed on

an object.

Vbcolor Determines the color of object using the name of color.

Qbcolor(x) Determines the color of object using the number (x) of color,

where x between (1to15).

RGB(Red,

Green, Blue)

Determines the colors, the range number for each color is

between (0 To 255).

Visible Determines whether or not an object is displayed. The Visible

property is set to (True or False).

For example the following code will change the form color to yellow every time

the form is loaded. Visual Basic-6 uses RGB(Red, Green, Blue) to determine the colors.

Page 42: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

42

The RGB code for yellow is 255,255,0. The code refer to the current form and Backcolor

is the property of the form's background color. The formula to assign the Backcolor is:

Form1.Backcolor=RGB(255,255,0) or Form1.Backcolor=VbYellow

Here are some of the common colors and the corresponding VBcolor (Qbcolor (vbcode))

and RGB codes. You can always experiment with other combinations, but remember the

maximum number for each color is 255 and the minimum number is 0.

Table (3-7) VBcolor

VBCode RGBcode Color Constant

0 0,0,0 Black vbBlack

1 0, 0, 255 Blue vbBlue

2 0,255,0 Green vbGreen

3 50,100,0 Cyan vbCyan

4 255, 165, 0 Brown vbBrown

5 255, 0, 255 Magenta vbMagenta

12 255,0,0 Red vbRed

14 255, 255, 0 Yellow VbYellow

15 255, 255, 255 White vbWhite

Example 3-5 make a program that allows the user to enter the RGB codes into three

different textboxes and when clicks the display color button, the background color of the

form will change according to the RGB codes. So, this program allows users to change

the color properties of the form at run time.

Solution:

1- Design

Page 43: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

43

2- Code writing :

Dim rgb1, rgb2, rgb3 As Integer

Private Sub Command1_click()

rgb1 = Val(Text1.Text)

rgb2 = Val(Text2.Text)

rgb3 = Val(Text13.Text)

Form1.BackColor = RGB(rgb1, rgb2, rgb3)

End Sub

3- Running the application.

Page 44: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

44

Practical part

Example 3-6: Design a form shown in figure below, with four commands button and one

label. Enter ―Name‖ in label1 from property window. When click on Command1 (Bold)

or Command2 (Italic) or Command3 (Underline), the properties of label1 are changed.

So when click on Command4 (Normal) replace the default properties of text are entered

in Label1.

Solution:

1- Design :

2- Code writing :

Page 45: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

45

3- Running the application.

Exercise:

3-6 Add four commands Button to the previous Example(3-5). When click on

Command (Larger) or Command (Smaller), the font size of label1 (caption) is

changed. Change the font color and the back ground of label1 by using

commands Red and BackGreen

respectively.

Page 46: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

46

Lecture 7

3-3 InputBox Function

InputBox function is used to input a value or character for one variable from

keyboard at running stage. The format is:

Variable-Name = InputBox (“phrase”, “Window Title”, “”)

For Example:

X=InputBox(―prompt‖,‖Title‖)

Note:

The type value for InputBox function is string value.

If we use InputBox directly without Dim, then InputBox‖NO NEED FOR

BRACKETS‖.

Ex:

Inputbox‖enter value of x,‖calculation‖

Example3-7: enter value of x using inputbox

Solution:

Private Sub Form_Load()

Dim x as integer

X=Inputbox("enter value of x", "calculation")

End Sub

Page 47: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

47

3-4 Message Boxes (MsgBox Function)

The objective of MsgBox is to produce a pop-up message box and prompt to click

on a command button before can continue. This format is as follows:

MsgBox “Prompt”, Style Value, “Title”

The first argument, Prompt, will display the message in the message box. The Style

Value will determine what type of command buttons appear on the message box. The

Title argument will display the title of the message board. The Style values are listed

below.

Table (11) Style values

Name Constant Style Value Buttons Displayed

VbOkonly 0 OK

Vbokcancel 1 OK ,Cancel

vbAbortRetryIgnor 2 Abort, Retry , Ignore

vbYesNoCancel 3 Yes, No, Cancel

vbYesNo 4 Yes, No

vbRetryCancel 5 Retry, Cancel

To make the message box looks more sophisticated, you can add an icon besides

the message. There are four types of icons available in VB6 as shown in following table.

Table (12) types of icons available.

Style Value Name Constant Icon

16 Vbcritical

32 Vbquestion

48 Vbexclamation

64 Vbinformation

Example 3-8: if we write the following statement then a message box will be appear as

shown below:

MsgBox "please close your program", 16, "Error"

or

MsgBox "please close your program", vbcritical, "Error"

Page 48: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

48

Example 3-9: show what appear after running the following statement:

MsgBox "are you sure you want to delete this file", 32 + 4, "delete"

Or

MsgBox "are you sure you want to delete this file",vbQuestion+vbYesNo,"delete"

Solution:

TestMsg is a variable that holds values that are returned by the MsgBox ( )

function. The values are determined by the type of buttons being clicked by the users. It

has to be declared as Integer data type in the procedure or in the general declaration

section. Table (13) shows the values, the corresponding named constant and buttons.

Table (13) Return Values and Command Buttons

Value

Named Constant

Button Clicked

1 vbOK OK button

2 vbCancel Cancel button

3 vbAbort Abort button

4 vbRetry Retry button

5 vbIgnore Ignore button

6 vbYes Yes button

7 vbNo No button

For example:

Private Sub form1_Load()

Page 49: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

49

Dim testmsg As Integer

TestMsg = MsgBox("Click to test", 1, "Test message")

If TestMsg = 1 Then MsgBox "You have clicked the OK button": End

If TestMsg = 2 Then MsgBox "You have clicked the Cancel button": Exit Sub

End Sub

Note: The statement ―Exit Sub‖ is defined to stop the program without close the form

window. While the statement “End” is stopped the program return to IDE window.

For example:

Private Sub Form1_Load()

Dim testMsg As Integer

testMsg = MsgBox ("Click to Test", vbYesNoCancel + vbExclamation, "Test

Message")

If testMsg = 6 Then MsgBox "You have clicked the yes button"

If testMsg = 7 Then MsgBox "You have clicked the NO button"

If testMsg =2 Then MsgBox "You have clicked the Cancel button")

End Sub

Page 50: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

50

Practical part

Example 3-10:Create a Visual Basic project to enter an angle value (Degree, Minutes,

and Seconds) by using inputbox, Design the program to find the value of angle (in

decimal degree) as the following equation. Display the result in MesgBox:

Decimal degree angle= Degree + (Minutes/60) + (Seconds/3600)

Solution:(soft copy)

Exercise:

3-7 Design a Visual Basic Program to calculate the average of 3 degree of student,

and then print the result by using MsgBox.

Page 51: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

51

Lecture 8

4- Making decision.

In this section, you will learn how programs use If...Then, If...Then...Else, and

If...Then...ElseIf statements to make decisions. You will learn how to compare values

using relational operators and build complex comparisons using arithmetic operators (see

section 3-1, 3). You will be introduced to the Select Case statement, OptionButton

(which allow the user to select one choice from many possible choices), check boxes

(which allow the user to make on/off or yes/no types of selections), Horizontal and

Vertical Scroll Bar(they are provide an intuitive way to move through a list of

information), Drive ListBox (Is used to display a list of drives available in your

computer), Dir ListBox( is used to display the list of directories or folder in a selected

drive),File ListBox(is used to display the list of files in a selected directory or folder),and

Timer(It may be used to measure execution time of code .

4-1 Conditional statements

They are used to cause certain actions within a program if a certain condition is

met. There are two types of conditional statements:

4-1-1 If statement:

If Condition Then Statement: Where, Condition is usually a comparison, but it can

be any expression that evaluates to a numeric value, this value as true or false. If

condition is True, Visual Basic executes all the statements following the Then

keyword.

Example 4-1: write a program to enter a mark of a student then print (pass) if

he successful.

Solution:

Dim x as integer

Private sub command1_click()

X= CInt(text1.text)

If x>= 50 then text2.text= "pass"

End sub

(If ..Then .. EndIf ) statement: The If...Then – EndIf Statement performs an

indicated action only when the condition is True; otherwise the action is skipped.

Page 52: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

52

If condition Then VB Expression End If

For example:

Dim X ,Y , Max

X =Val (Text1.Text ) : Y =Val (Text2.Text)

Max=X

If X< Y Then

Max=Y

EndIf

Text3.Text= Cstr (Max)

End Sub

(If – Then – Else) statement: The If – Then - Else statement allows the programmer

to specify that a different action is to be performed when a certain action specified by

the VB expression if the condition is True than when the condition is false, an

alternative action will be executed. The general format for the If - Then - Else

statement is

If condition Then VB expression

Else

VB expression

End If

Example 4-2: write a program to enter a mark of a student then print (pass) if he

successful and print (fail) otherwise.

Solution:

Dim x As Integer

Private Sub command1_click()

x = CInt(Text1.Text)

If x >= 50 Then

Text2.Text = "pass"

Else

Text2.Text = "fail"

End If

End Sub

Nested (If – Then – Else) statement: If there are more than two alternative choices,

using just If – Then - Else statement will not be enough. In order to provide more

choices, we can use If...Then...Else statement inside If...Then...Else structures.

Page 53: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

53

The general format for the Nested If...Then.. Else statement is:

Structure 1 Structure 2

If condition 1 Then If condition 1 Then

VB expression VB expression

Else ElseIf condition 2 Then

If condition 2 Then VB expression VB expression ElseIf condition 3 Then

Else VB expression

If condition 3 Then Else

VB expression VB expression

Else End If

VB expression

End If

End If

EndIf

Example 4-3: Write a program to enter the value of variable (Mark). Find the grade

using If – Block statement and display the value of grade in a text box. When the

value of variable (Mark) exceed 100, write a Message Box (Wrong entry, please Re-

enter the Mark). Design form window and select all the control objects are used.

Solution:

Private Sub Command1_click()

Dim Mark As Single , Grade as String

Mark = Val (Text1.Text)

If Mark >100 Then

Msgbox "Wrong entry, please Re-enter the mark", Vbcritical , " Error"

Text1.Text=" " : Text2.Text= " " : Exit Sub

ElseIf Mark >= 90 and Mark <=100 Then Grade="Excellent"

ElseIf Mark >= 80 Then Grade="Very Good"

ElseIf Mark>=70 Then Grade="Good"

ElseIf Mark>=60 Then Grade="Medium"

ElseIf Mark>=50 Then Grade="Pass"

Else Grade="Fail"

End If

Page 54: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

54

Text2.Text=Grade

End Sub.

Practical part

Example 4-4: Write a program to enter the value of two variables (X and Y). Find and

print the maximum value for two variables.

Solution:

Private Sub Command1_Click

Dim X , Y , Max

X =Val (Text1.Text )

Y =Val (Text2.Text)

Max=X

If y > x Then

Max= y

Text3.Text= Cstr (Max)

End Sub

Example 4-5: write a program to enter a user name and display the message (hello)

three times. The first one for (Mena), the second one for (Nastia) and the third for any

user as a guest.

Solution:

Dim x As String

Private Sub command1_click()

x = Text1.Text

If x = "Mena" Then

MsgBox "hello, Mena"

ElseIf x = "Nastia" Then

MsgBox "hello,Nastia"

Else

MsgBox "hello, guest"

End If

End Sub.

Page 55: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

55

Example 4-6: Create a Visual Basic project to solve for the roots of the quadratic

equation aX2+bX+c = 0 ,, using quadratic formula as:𝑋1,2=

− . Design the

program so that the values of coefficient a, b, and c are entered by using input box

statement. Display number of roots and value of roots in text boxes. When the value

of coefficient (a) equal to zero or(𝒃𝟐 − 𝟒ac) less than zero,write a message box to

enter a new value of coefficients or end the program.

Solution (soft copy)

M= 𝒃𝟐 – 𝟒ac

If a=0 or m < 0 then

Exercises:

4-1 Create a Visual Basic project to find the value of function f(Z) from the equations

are below. Write a code so that the value of variables Y and Z are entered into two

boxes. Display the value of function f (Z) in separate picture box when click

command button. Design form window and select all the control objects are used.

4-2 Use the Newton Raphson method to estimate the root of the function 𝑒−𝑋 = x ,

employing initial value of 𝑋old= 0.0 . Write visual Basic code to compute the root

𝑋new . Print the value of 𝑋new when the value of|𝑋old – 𝑋new| ≤ 0.0001. Design the

form with two text box and one command button.

Page 56: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

56

Lecture 9

4-1-2 Select case:

The If...Then...ElseIf statement allows your program to branch into one of

several possible paths. It performs a series of tests and branches when one of these

tests is true. The Select Case statement, which is a similar mechanism, tests the value

of an expression only once, and then uses that value to determine which set of

statements to branch to.

The format of the Select Case control structure is as follows:

Select Case test expression

Case expression list 1

VB statements

Case expression list 2

VB Statements

Case expression list 3

VB statements

Case expression list 4

Case Else

VB Statements

End Select

Page 57: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

57

Flowcharting the Select Case Statement The flowchart segment in Fig.(4-1)

shows the general form of a Select Case statement. The diamond represents the

test expression, which is compared to a series of values. The path of execution

follows the value matching the test expression. If none of the values matches a

test expression, the default path is followed (Case Else).

Fig.(4-1) Flowcharting the Select Case Statement

Example 4-7: write a program to give the evaluation for different marks as following

table, write a Message Box (Wrong entry, please Re-enter the Mark). Design form

window and select all the control objects are used.

Solution:

Private Sub Command1_click()

Dim Mark As Single

Grade as String

Mark = Val (Text1.Text)

Select Case Mark

Case 0 To 49

Grade="Fail"

Case 50 To 59

Grade="Pass"

Case 60 To 69

Grade="Medium"

Case 70 to 79

Page 58: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

58

Grade="Good

Case 80 To 89

Grade="Very Good"

Case 90 To 99

Grade="Excellent"

Case Else

Msgbox "Wrong entry, please Re-enter the mark", 16 , " Error"

Text1.Text=" " : Text2.Text= " " : Exit Sub

End Select

Text2.Text=Grade

End Sub

Practical part

Example 4-8: Design a form with four text boxes and three commands. Design the

program so that the values of num1, num2, and Symbol are entered into separate three

text boxes. Write a code to perform (add, subtract, multiply and divide) when pressing

on command (Calculate). Display the result in separate text box. The command

(Clear) used to clear values in text boxes. Click command (Exit) to end the program

and return to the project window.

Solution: Private Sub Calculate _Click()

Dim x As Double, y As Double, z

As Double

Dim symbol As String

x = CDbl(Text1.Text)

Symbol = Text2.Text

y = CDbl(Text3.Text)

Select Case Symbol

Case " + " : z = x + y

Case " - " : z = x – y

Case " * " : z = x * y

Case " / "

If y = 0 Then MsgBox "division by zero": Text3.Text = "" : GoTo 10

Else

z = x / y

Page 59: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

59

End if

Case Else

MsgBox "select any symbol (+,-,*,/)"

GoTo 10

End Select

Text4.Text = Str(z)

10 End Sub

Private Sub Clear_Click()

Text1.Text = ""

Text2.Text = ""

Text3.Text = ""

Text4.Text = ""

End Sub

Private Sub Exit_Click()

End

End Sub

Page 60: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

60

Lecture 10

4-2 Option Buttons and check boxes controls

Are useful when you want the user to select one choice from

several possible choices. Fig.(4-2) shows a group of option buttons. The user can select

either Coffee, Tea,

or Soft Drink by clicking the appropriate button.

Option buttons, are typically used in a group of two or more. At any one time, only

one button in the group can be "on". Clicking an option button turns it "on" and turns all

other buttons in the group "off"

Op

tion

Bu

tton

Ch

eck

Bo

x

Page 61: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

61

Fig. (4-3 Forms with option buttons (Radio Buttons)

Example 4-9: Create a Visual Basic Project includes one TextBox and three Option

Buttons to change the style of your full name.

Solution:

Option Button1:

Private Sub Option1_Click()

Text1.FontBold = True

Text1.FontItalic = False

Text1.FontUnderline = False

End Sub

Option Button2:

Private Sub Option2_Click()

Text1.FontBold = False

Text1.FontItalic = True

Text1.FontUnderline = False

End Sub

3Option Button

Private Sub Option3_Click()

Text1.FontBold = False

Text1.FontItalic = False

Text1.FontUnderline = True

End Sub

CheckBox Control:

The CheckBox control is similar to the OptionBoutton, except that a list of choices

can be made using check boxes where you cannot choose more than one selection using

an OptionButton. By ticking the CheckBox the value is set to True. This control can also

be grayed when the state of the CheckBox is unavailable, but you must manage that state

through code.

Example 4-10: repeat Example 4-9, by using CheckBoxes.

Solution: Private Sub Check1_Click()

Text1.FontBold = Check1.Value

End Sub

Page 62: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

62

Private Sub Check2_Click()

Text1.FontItalic = Check2.Value

End Sub

Private Sub Check3_Click()

Text1.FontUnderline = Check3.Value

End Sub

Practical part

Example 4-11: Write a program to enter two numbers and compute multiplication and

division operations using option button with display the phrase (illegal division

operation) when the denominator is zero.

Solution:

Dim a, b, c As Single

Private Sub command1_click()

a = Val(Text1.Text)

b = Val(Text2.Text)

If Option1.Value=true Then

c = a * b

Text3.Text = CStr(c)

Else

If b <> 0 Then

c = a / b

Text3.Text = CStr(c)

Else

Text3.Text = "illegal division operation"

End If

End If

End Sub

Page 63: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

63

Exercise

4-4 For a simply supported beam subjected to a uniform load (W) on the length of

span (L) and a concentrated load (P) on a mid span (L/2). When the user click

checkbox1, enter the value of (P) and display the value of bending moment (Mom)

in a separate text box, when the user click on the checkbox2, enter the value of (W)

and display the value of bending moment (Mom) in a separate textbox. Write a

program in a separate command button (Calculate) to find the value of (Mom) at

mid span of beam subjected to (W) or (P) or both of them.

The Bay City Health and Fitness Club charges the following monthly

membership rates:

Standard adult membership: $40/month

Student: $25/month

Senior citizen (age 65 and over): $30/month

The club also offers the following optional services, which increase the base

monthly fee:

Yoga lessons: add $10 to the monthly fee

Karate lessons: add $30 to the monthly fee

Personal trainer: add $50 to the monthly fee

The manager of the club has asked you to create a Health Club Membership Fee

Calculator application. It should allow the user to select a membership rate, select

Page 64: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

64

optional services, and enter the number of months of the membership. It should

calculate the member‘s monthly and total charges for the specified number of

months. The application should also validate the number of months entered by the

user. An error message should be displayed if the user enters a number less than 1

or greater than 24. (Membership fees tend to increase every two years, so there is a

club policy that no membership package can be purchased for more than 24

months at a time.

Page 65: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

65

Lecture 11

4-3 ListBox and ComboBox Controls

ListBox:

A listBbox 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 of the most recently selected item in list. If no item is

selected, 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.

Text Text of most recently selected item.

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 lstExample.List(4) from list box

Page 66: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

66

Example 4-12 : Write a program in VB6 including one TextBox, one ListBox and one

Command, showing that when inputting four colors names from TextBox to the ListBox

and select any color name in the ListBox then the Form background color will change.

Solution:

Command1:

Private Sub Command1_Click()

List1.AddItem Text1.Text

Text1.Text = ""

End Sub

List1:

Private Sub List1_Click()

If List1.Text = "Red" Then

Form1.BackColor = vbRed

End If

If List1.Text = "Green" Then

Form1.BackColor = vbGreen

End If

If List1.Text = "Blue" Then

Form1.BackColor = vbBlue

End If

If List1.Text = "Magenta" Then

Form1.BackColor = vbMagenta

End If

End Sub

ComboBox:

The comboBox is similar to the list box. The differences are a comboBox includes a

textBox on top of a list box and only allows selection of one item. In some cases, the user

can type in an alternate response.

Note: ComboBox properties are nearly identical to those of the list box, with the deletion

of the MultiSelect property and the addition of a Style property.

List Box Properties

Style Selects the combo box form.

Style = 0, Dropdown combo; user can change

selection.

Page 67: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

67

Style = 1, Simple combo; user can change selection.

Style = 2, Dropdown combo; user cannot change selection.

Examples

cboExample.AddItem "This is an added item" ' adds text string to list

cboExample.Clear ' clears the combo box

cboExample.RemoveItem 4 ' removes cboExample.List(4) from list box

Example4-13: design a program reading Student Name in a TextBox, Gender in a

ComboBox, Age in a ComboBox, Department in a ListBox and print the output in a

TextBox with red color font.

Solution:

Form1:

Private Sub Form_Load()

Combo1.AddItem "Male"

Combo1.AddItem "Female"

Combo2.AddItem "19"

Combo2.AddItem "20"

Combo2.AddItem "21"

Combo2.AddItem "22"

List1.AddItem "Metal"

List1.AddItem "Non Metal"

End Sub

Command1:

Private Sub Command1_Click()

Text2.Text = Text1.Text + " " + Combo1.Text + " " + Combo2.Text + " " +

List1.Text

End Sub

Page 68: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

68

Practical part

Example 4-14 :Flight Planner Start a new project. In this example, you select a destination city,

a seat location, and a meal preference for airline passengers, Place a list box, two combo boxes,

three label boxes and two command buttons on the form. The form should appear similar to

this:

Solution :

Private Sub Form_Load()

‘Add city names to list box

lstCities.Clear

lstCities.AddItem "San Diego"

lstCities.AddItem "Los Angeles"

lstCities.AddItem "Orange County"

lstCities.AddItem "Ontario"

lstCities.AddItem "Bakersfield"

lstCities.AddItem "Oakland"

lstCities.AddItem "Sacramento"

lstCities.AddItem "San Jose"

lstCities.AddItem "San Francisco"

lstCities.AddItem "Eureka"

lstCities.AddItem "Eugene"

lstCities.AddItem "Portland"

lstCities.AddItem "Spokane"

lstCities.AddItem "Seattle"

lstCities.ListIndex = 0

‘Add seat types to first combo box

cboSeat.AddItem "Aisle"

Page 69: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

69

cboSeat.AddItem "Middle"

cboSeat.AddItem "Window"

cboSeat.ListIndex = 0

‘Add meal types to second combo box

cboMeal.AddItem "Chicken"

cboMeal.AddItem "Mystery Meat"

cboMeal.AddItem "Kosher"

cboMeal.AddItem "Vegetarian"

cboMeal.AddItem "Fruit Plate"

cboMeal.Text = "No Preference"

End Sub

This code simply initializes the list box and the list box portions of the two combo

boxes.

Attach this code to the cmdAssign_Click event:

Private Sub cmdAssign_Click()

‗Build message box that gives your assignment

Dim Message As String

Message = "Destination: " + lstCities.Text + vbCr

Message = Message + "Seat Location: " + cboSeat.Text +vbCr

Message = Message + "Meal: " + cboMeal.Text + vbCr

MsgBox Message, vbOKOnly + vbInformation, "Your

Assignment"

End Sub

When the Assign button is clicked, this code forms a message box message by Concatenating

the selected city (from the list box lstCities), seat choice (from cboSeat), and the meal

preference (from cboMeal).

Attach this code to the cmdExit_Click event:

Private Sub cmdExit_Click()

End

End Sub.

Page 70: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

70

bLecture 12

4-4 Horizontal and Vertical Scroll Bar control

(HScrollBar & VScrollBar)

Horizontal and vertical scroll bars are widely used in Windows applications.

Scroll bars provide an intuitive way to move through a list of information. Both type of scroll bars are comprised of three areas that can be clicked, or dragged, to change the scroll

bar value.

Example 4-15: Using Scroll Bar, change the TextBox font size and forecolor

Solution:

Form1:

Private Sub Form_Load()

HScroll1.Min = 1

HScroll1.Max = 100

End Sub

Page 71: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

71

HScroll1:

Private Sub HScroll1_Change()

Text1.FontSize = HScroll1.Value

Text1.ForeColor = RGB(Rnd * 255, Rnd * 255, Rnd * 255)

End Sub

4-5 Displaying of drives, folders, and files control.

The Drive ListBox

Is used to display 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 drive from your

computer

The Dir ListBox

is used to display the list of directories or folder 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.

The File ListBox

is used to display the list of files in a selected directory or folder. When you place this

control into the form and run the program, you will be able to a list of files in a selected

directory.

if Pattern = *.* showing all files.

if Pattern = *. bmp;*.gif;*.jpg showing only picture files.

if Pattern = *. mp3;*.wav showing only audio files.

if Pattern = *. mp4;*.avi;*.wmv showing only video files.

Example 4-16 : showing Drive ListBox, DirListBox and display an image

according to the File ListBox.

Page 72: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

72

Timer

Solution:

Dir1:

Private Sub Dir1_Change()

File1.Path = Dir1.Path

End Sub

Drive1:

Private Sub Drive1_Change()

Dir1.Path = Drive1.Drive

End Sub

File1:

Private Sub File1_Click()

Image1.Picture = LoadPicture(Dir1.Path + "\" + File1.FileName)

End Sub

4-6 Timer controls

Timer returns the time in millisecond. It may be used

to measure execution time of code (program efficiency).

Property name Objective and code interval To repeat the code according to event. It takes

an integer values (0-65535) and measured in

millisecond (1000 milliseconds = 1 second).

enabled timerno.. Enabled =true or false

Page 73: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

73

Note: 1- It is not visible to the user at Run-time

2- You can write the code of an action in the Timer's Timer event if there is no

Command Button for these actions.

Practical part

Example 4-17: design electronic clock to display the time in seconds.

Solution:

Private Sub Timer1_Timer()

Label1.Caption = Time

End Sub

Example 4-18: Design a form to display "faculty of W.R engineering" such that when

click on command button "start" the color of " faculty of W.R engineering " changed

randomly every second.

Solution:

Page 74: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

74

Private Sub Command1_Click()

Timer1.Enabled = True

End Sub

Private Sub Timer1_Timer()

t = Rnd * 15

Label1.ForeColor = QBColor(CInt(t))

End Sub

Example 4-19: Design A program to make your full name flashing in a Label

Solution: Private Sub Form_Load() Timer1.Interval = 1000

Timer2.Interval = 1020

Timer3.Interval = 1040 End Sub Timer1: Private Sub Timer1_Timer() Label1.Visible = Not (Label1.Visible) End Sub Timer2: Private Sub Timer2_Timer() Label2.Visible = Not (Label2.Visible) End Sub

Timer3: Private Sub Timer3_Timer() Label3.Visible = Not (Label3.Visible) End Sub

Timer1

interval 1000

enabled false

Label1

Caption faculty of

W.R

engineering

Command1

caption start

Page 75: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

75

Exercise:

4-6 Using Scroll Bar, change the label font size and forecolor.

4-7 design a simple Count-Down display in a label, with STOP and

Continue Buttons.

4-8 Design a Stopwatch (Minutes, Seconds and parts of seconds) using

VB6, including Commands (Start, Stop, Continue and Reset)

Page 76: Lecture1 1- Introduction to Programming and Visual Basic basig 6...Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions,

W.R.E faculty by: assist lect. Mohammed Q.k. AL-qasim green university

76