Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft...

47
Visual Basic 6.0 1430/1431 2 nd term 1

Transcript of Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft...

Page 1: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

1

Visual Basic 6.0

1430/14312nd term

Page 2: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

2

Course Objectives• Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an

application tool.• Understand the Visual Basic event-driven programming concepts, terminology,

and available tools.• Learn the fundamentals of designing, implementing, and distributing a Visual

Basic application.• Learn to use the Visual Basic toolbox.• Learn to modify object properties.• Learn object methods.• Use the menu design window.• Understand proper debugging and error-handling procedures.• Gain a basic understanding of database access and management using data bound

controls.• Obtain an introduction to ActiveX controls and the Windows Application

Programming Interface (API).

Page 3: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

3

What is Visual Basic?

• Visual Basic Is a tool that allows you to develop Windows (Graphic User Interface - GUI) applications. The applications have a familiar appearance to the user.

Page 4: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

4

What is Visual Basic?• Visual Basic is event-driven, meaning code

remains idle until called upon to respond to some event (button pressing, menu selection, ...). Visual Basic is governed by an event processor. Nothing happens until an event is detected. Once an event is detected, the code corresponding to that event (event procedure) is executed. Program control is then returned to the event processor.

Page 5: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

5

Some Features of Visual Basic• Full set of objects - you 'draw' the application• Lots of icons and pictures for your use• Response to mouse and keyboard actions• Clipboard and printer access• Full array of mathematical, string handling, and graphics functions• Can handle fixed and dynamic variable and control arrays• Sequential and random access file support• Useful debugger and error-handling facilities• Powerful database access tools• ActiveX support• Package & Deployment Wizard makes distributing your

applications simple

Page 6: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

6

Structure of a Visual Basic Application

Get back to Contents

Page 7: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

7

Structure (continued)

Form

Control Button

Window

Get back to Contents

Page 8: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

8

Frame

Option Button

Label

Window

Form

Structure (continued)

Command Button

Get back to Contents

Page 9: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

9

The code window

Page 10: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

10

Contents of the Application (the Project)

• Forms - Windows that you create for user interface• Controls - Graphical features drawn on forms to allow user interaction (text boxes,

labels, scroll bars, command buttons, etc.) Forms and Controls are objects.)• Properties - Every characteristic of a form or control is specified by a property.

Example properties include names, captions, size, color, position, and contents. Visual Basic applies default properties. You can change properties at design time or run time.

• Methods - Built-in procedure that can be invoked to impart some action to a particular object.

• Event Procedures - Code related to some object. This is the code that is executed when a certain event occurs.

• General Procedures - Code not related to objects. This code must be invoked by the application.

• Modules - Collection of general procedures, variable declarations, and constant definitions used by application.

Page 11: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

11

User Interface Main Window

Tool Box

Project Explorer

Properties Window

Form Layout

Project Window

Page 12: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

12

Main Window

• The Main Window consists of the title bar, menu bar, and toolbar.

Page 13: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

13

Start Visual Basic 6

Page 14: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

14

Page 15: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

15

Contents of the Main Window of VB6

The menu bar has drop-down menus from which you control the operation of the Visual Basic environment.

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

Page 16: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

16

Add project

Add form

Menu editor

Open project

Save project

Code editor tasks

Run

Pause

Stop

Project explorer

Properties window

Form layout window

Object browser

Data view window

Visual component manager

Toolbox

Page 17: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

17

ToolboxThe Toolbox is the selection menu for controls used in your

application.

Page 18: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

18

Properties window

The Properties Window is used to establish initial property values for objects. The drop-down box at the top of the window lists all objects in the current form. Two views are available: Alphabetic and Categorized. Under this box are the available properties for the currently selected object.

Page 19: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

19

The Form Layout Window shows where (upon program execution)your form will be displayed relative to your monitor’s screen:

The Project Window displays a list of all forms and modules making up your application. You can also obtain a view of the Form or Code windows (window containing the actual Basic coding) from the Project window.

Page 20: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

20

Example: Stopwatch application

The application is used to calculate the time elapsed between two events. The user starts a timer, once the second event tops, the user stops the timer, the time duration is displayed.The steps are:1. Drawing controls2. Setting properties of the controls3. Writing code

Page 21: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

21

1. Drawing Controls

1. Start new project2. Draw 3 command buttons on the form3. Draw 6 labels on the form

Page 22: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

22

2. Setting properties of the controls

The properties of the controls can be modified in two different ways:• Setting properties during design time.

In this way you click on the object (form or control) in the form window, then click on the Properties Window or the Properties Window button in the tool bar.

• Setting properties during run time. In this way you can set or modify properties while your application is running. To do this, you must write some code. The code format is:

ObjectName.Property = NewValueSuch a format is referred to as dot notation. For example, to change the BackColor property of a form name frmStart, you may type:

frmStart.BackColor = BLUE

Page 23: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

23

Setting properties during design time

• Here we selected the form window and clicked on the properties window. Notice that the from name here (which is the most important property) is frmStopWatch.

• Object names can be up to 40 characters long, must start with a letter, must contain only letters, numbers, and the underscore (_) character.

Page 24: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

24

Setting Properties in stopwatch exampleThe following table shows the properties you are going to change for the objects you put on the form.

Name Caption Border Style

Form1 frmStopWatch Stopwatch Application 1-Fixed Single

Command1 cmdStart &Start Timing

Command2 cmdEnd &End Timing

Command3 cmdExit E&xit

Label1 Start Time

Label2 End Time

Label3 Elapsed Time

Label4 lblStart 1-Fixed Single

Label5 lblEnd 1-Fixed Single

Label6 lblElapsed 1-Fixed Single

PropertyObject

Page 25: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

25

Writing Code

• Variable Declaration– Variables are used by Visual Basic to hold information needed by the

application.

• Rules used in naming (declaring) variables:I. No more than 40 charactersII. They may include letters, numbers, and underscore (_)III. The first character must be a letterIV. You cannot use a reserved word (word needed by Visual Basic)

Page 26: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

26

Visual Basic Data Types

Data Suffix

Boolean None

Integer %

Long (Integer) &

Single (Floating) !

Double (Floating) #

Currency @

Date None

Object None

String

Variant None

Page 27: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

27

There are three ways for a variable to be typed (declared):1. Default2. Implicit3. Explicit

If variables are not implicitly or explicitly typed, they are assigned the variant type by default. The variant data type is a special type used by Visual Basic that can contain

numeric, string, or date data.

Private Sub Command1_Click()a% = Text1.TextText2.Text = a ^ 2End Sub

Private Sub Command1_Click()Static a As Integera = Text1.TextText2.Text = a ^ 2End Sub Implicit declaration of the

variable a.

Page 28: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

28

Option ExplicitDim a As IntegerPrivate Sub Command1_Click()a = Text1.TextText2.Text = a ^ 2End SubPrivate Sub Command3_Click()a = Text1.TextText3.Text = 2 * a + 5End Sub

Explicit declaration of the variable a.

Page 29: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

29

Variable Scope

Page 30: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

30

Global Declaration of a variable

• For the variable to be declared globally, it should be declared in a module, to create a module,

Page 31: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

31

How to Create a Module

In the module declare the variables by writing the following line:Global a, b, c As LongDim c As IntegerIn this way the variables will be kept in the whole code as they been defined.

Page 32: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

32

The Visual Basic Language

• Visual Basic Statements and ExpressionsThe simplest statement is the assignment statement. It consists of a variable name, followed by the assignment operator (=), followed by some sort of expression.• StartTime = Now• Explorer.Caption = "Captain Spaulding"• BitCount = ByteCount * 8• Energy = Mass * LIGHTSPEED ^ 2• NetWorth = Assets – LiabilitiesStatements normally take up a single line with no terminator. Statements can be stacked by using a colon (:) to separate them. Example:• StartTime = Now : EndTime = StartTime + 10

Page 33: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

33

• Visual Basic Operatorsarithmetic operators:• The simplest operators carry out arithmetic operations. These operators in their

order of precedence are:Operator Operation

1. ^ Exponentiation2. * / Multiplication and division3. \ Integer division (truncates)4. Mod Modulus5. + - Addition and subtractionParentheses around expressions can change precedence.comparison operators:

Operator Comparison1. > Greater than2. < Less than3. >= Greater than or equal to4. <= Less than or equal to5. = Equal to6. <> Not equal toThe result of a comparison operation is a Boolean value (True or False).

Page 34: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

34

logical operators

Operator Operation1. Not Logical not2. And Logical and3. Or Logical or

• The Not operator simply negates an operand.• The And operator returns a True if both operands are True

else, it returns a False.• · The Or operator returns a True if either one of its operands

is True, else it returns a False.Logical operators follow arithmetic operators in precedence.

Page 35: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

35

Visual Basic Functions

Some of the built in visual basic functions are given here for example

Function Value returnedAbs Absolute value Asc ASCII or ANSI code of a character Chr Character corresponding to a given ASCII or ANSI code Cos Cosine of an angle Date Current date as a text string Format Date or number converted to a text string Left Selected left side of a text string Len Number of characters in a text string Mid Selected portion of a text string Now Current time and date Right Selected right end of a text string Rnd Random number Sin Sine of an angle Sqr Square root of a number Str Number converted to a text string Time Current time as a text string Timer Number of seconds elapsed since midnight Val Numeric value of a given text string

Page 36: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

36

Visual Basic Symbolic Constants

Functions and objects always require data arguments that affect their operation and return values you want to read and interpret. These arguments and values are constant numerical data and difficult to interpret based on just the numerical value. To make these constants more understandable, Visual Basic assigns names to the most widely used values, these are calledsymbolic constants. You can find such constants here.

Page 37: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

37

MsgBox Arguments Constants

Constant Value Description

vbOKOnly 0 OK button only (default)

vbOKCancel 1 OK and Cancel buttons.

vbAbortRetryIgnore 2 Abort, Retry, and Ignore buttons.

vbYesNoCancel 3 Yes, No, and Cancel buttons.

vbYesNo 4 Yes and No buttons.

vbRetryCancel 5 Retry and Cancel buttons.

vbCritical 16 Critical message.

vbQuestion 32 Warning query.

vbExclamation 48 Warning message.

vbInformation 64 Information message.

vbDefaultButton1 0 First button is default (default)

vbDefaultButton2 256 Second button is default.

vbDefaultButton3 512 Third button is default.

vbApplicationModal 0 Application modal message box

vbSystemModal 4096 System modal message box.

Page 38: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

38

Example: Finding the roots of the quadratic equation

Find the roots of the quadratic equation

Given the parameters a, b, and c.Check if the parameters give imaginary roots, if any, find the absolute values.The interface should be like shown

0cbxax2

a2

ac4bb2,1x

2

Page 39: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

39

Page 40: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

40

Example: Temperature conversion

The Fahrenheit temperature is converted into Celsius by the following formula

The interface should look like shown here95

*)32F(C

Page 41: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

41

Creating File for EditingA file is being creating for input, output and as file editor.1. Create new project2. On the form draw a textbox as large as the size of

the form3. Add from the tool box a COMMON DIALOG BOX. If

it is not there, follow the steps belowa. From PROJECT menu select componentsb. Scroll the components to MICROSOFT DIALOG BOX and

check the box .c. It is now on the toolbox bar.

4. Notice its name which you will use in the code.5. Now, use from TOOLS the menu editor to add (file)

and (format) menus.

Page 42: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

42

File Menu

Use the MNUE EDITOR to write the file menu components.The code:•Exit codeClick on exit in the created file menu, and start writing the code for ending the run.

'Make sure user really wants to exitDim Response As IntegerResponse = MsgBox("Are you sure you want to exit the note editor?", vbYesNo + vbCritical + vbDefaultButton2, "Exit Editor")If Response = vbNo ThenExit SubElseEndEnd If

Page 43: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

43

• New codeClick on New in the created file menu, and start writing the code for creating new file.

'If user wants new file, clear out textDim Response As IntegerResponse = MsgBox("Are you sure you want to start a new file?", vbYesNo + vbQuestion, "New File")If Response = vbYes ThentxtEdit.Text = ""ElseEnd If

Page 44: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

44

• Save codeClick on Save in the created file menu, and start writing the code for saving the created file with extension ned (it is arbitrary as long as you don’t select a known format. The common dialog box here is named cdlFiles.

cdlFiles.Filter = "Files (*.ned)|*.ned"cdlFiles.DefaultExt = "ned"cdlFiles.DialogTitle = "Save File"cdlFiles.Flags = cdlOFNOverwritePrompt + cdlOFNPathMustExistOn Error GoTo No_SavecdlFiles.ShowSaveOpen cdlFiles.FileName For Output As #1Print #1, Val(txtEdit.Text)Close 1Exit SubNo_Save:Resume ExitLineExitLine:Exit Sub

Page 45: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

45

cdlFiles.Filter = "Files (*.ned)|*.ned"cdlFiles.DefaultExt = "ned"cdlFiles.DialogTitle = "Open File"cdlFiles.Flags = cdlOFNFileMustExist + cdlOFNPathMustExist + cdlOFNHelpButtonOn Error GoTo No_OpencdlFiles.ShowOpenOpen cdlFiles.FileName For Input As #1txtEdit.Text = Input(LOF(1), 1)Close 1Exit SubNo_Open:Resume ExitLineExitLine:Exit Sub

• Open codeClick on Open in the created file menu, and start writing the code for opening a saved file with extension ned (it is arbitrary as long as you don’t select a known format. The common dialog box here is named cdlFiles.

Page 46: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

46

Format Menu

• Use the MNUE EDITOR to write the format menu components (Bold, Underline, Italic, Size, Small, Medium and Large).

The code:Bold codeClick on Bold in the created format menu, and start writing the code for Bold.

mnuFmtBold.Checked = Not (mnuFmtBold.Checked)txtEdit.FontBold = Not (txtEdit.FontBold)

The code:Underline codeClick on Underline in the created format menu, and start writing the code for Underline.

mnuFmtUnderline.Checked = Not (mnuFmtUnderline.Checked)txtEdit.FontUnderline = Not (txtEdit.FontUnderline)

Page 47: Visual Basic 6.0 1430/1431 2 nd term 1. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool.

47

• mnuFmtItalic.Checked = Not (mnuFmtItalic.Checked)• txtEdit.FontItalic = Not (txtEdit.FontItalic)

The code:Italic codeClick on Italic in the created format menu, and start writing the code for Italic.

The code:Small codeClick on Size submenu Small in the created format menu, and start writing the code for giving the font a small size .Do the same steps for both Medium and Large submenus, giving in each case the value of the font to be 12 and 18, respectivily.

mnuFmtSizeSmall.Checked = TruemnuFmtSizeMedium.Checked = FalsemnuFmtSizeLarge.Checked = FalsetxtEdit.FontSize = 8