Beruflich Dokumente
Kultur Dokumente
CHAPTER 1 Introduction to Visual Basic 6.0 Visual basic is a high level programming language (HLL) developed from the BASIC programming language. VB programming is done in a graphical environment, also known as GUI (Graphical User Interface). Visual Basic enables the user to design the user interface quickly by drawing and arranging the user elements. The Window GUI defines how the various elements such as FORMS and CONTROLS look and function. Visual Basic is an event-driven programming language. Procedural vs. OOP vs. event-driven programming language In the Procedural languages such as Basic, C, COBOL, etc the program specifies exact sequence of all operations. Program logic determines the next instruction to execute in response to conditions and user request. OOPs define software as a collection of discrete oblects that specify both data structure and behavior. OOPs Identify following aspects: Data abstraction, Inheritence, Polymorphism, Encapsulation (information hiding)etc. Event Driven Programming: Events are the actions that are performed by the user during the application usage. If a user clicks a mouse button on any object then the Click event occurs. If a user moves the mouse then the mouse move event occurs Any programming language, which uses these events to run a specific portion of the program, will be called event driver programming. The GUI based programs are all developed using event driver programming. In the event driven model programs are no longer procedural; the do not follow a sequential logic. The programmers do not take control and determine the sequence of execution of program. Instead, the user can press and click on various button and boxes in a window. Each user action can cause an event to occur, which triggers a Basic procedure (code) that you have written. The Object model in VB 6: In VB you will work with Objects, which have Properties and methods. OBJECTS: Think of an Object as a thing. Examples of Objects are Forms and Controls. Forms are the windows and dialog boxes you place on the screen; Controls are the elements you place inside a form, such as text coxes, command button, etc. Properties: Properties tell something about the Object, such as its name, color, size, etc or how it will behave. To refer to a property of an Object, VB syntax is: Object.Property For example, to refer to text property of Text Box named text1, we use text1.Text Methods: Actions associated with the objects are called Methods. Example: Move, Print, Resize, Clear.
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -1-
VB6 Environment / IDE (Integrated Development Environment) The VB6 environment is where you create and test your projects. Fig 2 shows various windows in VB6 environment. Each window can be moved, resized, opened, or closed. Various windows in VB6 environment are: Main VB Window The main VB Window holds the VB Menu bar, the toolbar, and the form location and size information FORM WINDOW The form window is where you design the forms that makes up your user interface. When you begin a new project, VB gives your form name the default name Form1. The Project Explorer Window This window holds the filenames for the files included in your project.
Fig 3: Project Explorer Window The Properties Window We use the properties window to set the properties for the objects in the project. The Form Layout Window The position of the form in this window determines the position of the form on the desktop when execution of the project begins. The Toolbox Toolbox window contains a set of controls which are used to customize forms. Using this controls user can create an interface between user and the application Figure 4 Toolbox windows with its controls available commonly.
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -2-
Control Pointer PictureBox TextBox Frame CommandButton CheckBox OptionButton ListBox ComboBox HScrollBar VScrollBar Timer DriveListBox DirListBox FileListBox Shape Line Image Data OLE
Description used to interact with the controls on the form used to display images used to accept user input which can display only editable text used to group other controls used to initiate an action by pressing on the button used to do a choice for user (checked or unchecked) used in groups where one at a time can be true used to provide a list of items used to provide a short list of items a horizontal scrollbar a vertical scrollbar used to perform tasks in specified intervals. used to access to the system drives used to access to the directories on the system used to access to the files in the directory used to draw circles, rectangles, squares, ellipses used to draw lines used to display images. But less capability than the PictureBox used to connect a database used to interact with other windows applications
Label used to display texts which cannot be edited The Toolbar We can use the buttons on the toolbar for frequently used operations.
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -3-
VISUAL BASIC CODE STATEMENTS The basic program in VB requires 3 statements: 1.The Remark Statements Remark statements are sometimes called as COMMENTS, are used for project documentation only. They are not considered executable and have no effect when the project runs. The purpose of remarks is to make the project more readable and understandable by the person who reads it. VB remarks begin with an apostrophe. Example: this project is made in VB6 Exit the project Text1.Text=Welcome set the text property of text1 to welcome. 2. The Assignment Statements The assignments statement assigns a value to a property or variable. Syntax: [Let] Object.Property = value The LET is optional and may be included if you wish. Example: Text1.Text=welcome Let lblName = ABC Lblname.FontSize = 12 3. The END statement The END statement stops execution of the project. Example, Include an END statement in the sub procedure for an EXIT button
FIRST VB PROJECT Getting started To open the Visual Basic environment and to work with it select and click on Microsoft Visual Basic 6.0 in the start menu. When Visual Basic is loaded the New Project dialog shown in figure 1.1 will be displayed with the types available in Visual Basic. You can notice that Standard Exe is highlighted by default. Standard Exe allows the user to create standard executable. Standard executable is a type which has most of the common features of Visual basic
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -4-
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -5-
Private Sub cmdExit_Click() txtName.Text = "Welcome to VB 6" End Sub Private Sub cmdOK_Click() End End Sub Run The Project Press F5 or Start button on the toolbar to run the project. Save the project While saving the project, The Project file is saved with extension .vbp The form file is saved with extension .frm The module file is saved with extension .bas The custom controls is saved with extension .ocx Naming Rules and Convention for Object: Naming Rules: When you select names for object, VB requires the name to begin with a letter. The name can be up to 40 characters in length and can contain letter, digits and underscore. An object name cannot include a space or punctuation marks. The naming Convention Always begin a name with lowercase 3 letter prefix, which identifies the object type (such as label, command button, etc.) and capitalize the first character after the prefix( the real name of the object). For names with multiple words, capitalize each word in the name. All names must be meaningful and indicate the purpose of the Object. Example: lblMessage, cmdOk, cmdExit, lblDiscountRate, etc. Object naming conversions of controls (prefix) Form -frm Label -lbl TextBox -txt CommandButton -cmd CheckBox -chk OptionButton -opt ComboBox -cbo ListBox -lst Frame -fme PictureBox -pic Image -img Shape -shp Line -lin
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -6-
TYPES OF ERRORS 1. COMPILE ERRORS The VB attempts to convert your program code to machine language (called compiling the code) ,it finds any compile errors .You get the compile errors when you break the syntax rules of Visual basics and sometimes when you use an illegal object or property. For example, try spelling end as ennd. txtName.Text=ABC is correct but txt,name=ABC is incorrect. 2. RUN-TIME ERRORS If your projects halts during execution, thats run time errors. VB displays a dialog box and goes into break mode and highlights the statement causing the error. Statements that cannot be executed correctly causes runtime errors. Such statements are compiled correctly but fail too execute. Examples: calculation with non-numeric value, divide by zero, square of negative number. 3. LOGICAL ERRORS With logic errors, a project run but produces incorrect results. Example, result of a calculation is incorrect or the wrong text appears or the text is OK but appears in the wrong location. CONTEXT SENSITIVE HELP VB 6 provides a great HELP section, if MSDN Library is installed in your machine. For Context Sensitive Help, select a VB object, such as Text Boxes, or place the insertion point in a word in the editor and Press F1. The MSDN Library viewer will open on the correct page, if possible, saving you a search.
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -7-
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -8-
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -9-
LINE CONTROL The line control is used to create simple line segments on a form, a frame, or in a picture box. You can control the position, length, color, and style of line controls to customize the look of applications. CHANGING FONT PROPERTIES OF CONTROLS At design time use the Font property to open Font dialog. At runtime we use Font Object. A font object has several properties including Name, size, Bold, Italic, Underline, etc. Example: Object.Font.Bold=True Object.Font.Italic=True Object.Font.UnderLine=True Object.Font.Size=12 CHANGING COLOR PROPERTIES OF CONTROLS At designtime we can use ForeColor property to change the color of text/caption in control. At runtime we can use ForeColor property. The VB6 provides 8 color constants to use: vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, vbWhite Example: txtName.ForeColor=vbRed lblMessage.ForeColor=vbGreen
Private Sub chkBold_Click() Text1.Font.Bold = True End Sub Private Sub chkItalic_Click() Text1.Font.Italic = True End Sub Private Sub chkUnderline_Click() Text1.Font.Underline = True End Sub Private Sub optRed_Click() Text1.ForeColor = vbRed End Sub Private Sub optGreen_Click() Text1.ForeColor = vbGreen End Sub Private Sub optBlue_Click() Text1.ForeColor = vbBlue End Sub
Private Sub cmdRectangle_Click() Shape1.Shape = 0 End Sub Private Sub cmdSquare_Click() Shape1.Shape = 1 End Sub Private Sub Oval_Click() Shape1.Shape = 2 End Sub Private Sub cmdCircle_Click() Shape1.Shape = 3 End Sub Private Sub cmdRoundedRectangle_Click() Shape1.Shape = 4 End Sub Private Sub cmdRoundedSquare_Click() Shape1.Shape = 5 End Sub DEFINING KEYBOARD ACCESS KEYS Many people prefer to use the keyboard, rather than a mouse, for most operations. You can make your program respond to keyboard by defining access keys. For example: In the below diagram, you can select the OK button by pressing alt+o and the exit button by pressing alt+e.
The highest TabIndex setting is always one less than the number of controls in the tab order (because numbering starts at 0). Even if you set the TabIndex property to a number higher than the number of controls, Visual Basic converts the value back to the number of controls minus 1. Note Controls that cannot get the focus, as well as disabled and invisible controls, don't have a TabIndex property and are not included in the tab order. As a user presses the TAB key, these controls are skipped. Removing a Control from the Tab Order Usually, pressing TAB at run time selects each control in the tab order. You can remove a control from the tab order by setting its TabStop property to False (0). A control whose TabStop property has been set to False still maintains its position in the actual tab order, even though the control is skipped when you cycle through the controls with the TAB key. CREATING TOOLTIPS The word or short phrase that describes the function of a toolbar button or other tool. The ToolTip appears when you pause the mouse pointer over an object.
ToolTipText Property Returns or sets a ToolTip. At design time you can set the ToolTipText property string in the control's properties dialog box. At Run-time: object.ToolTipText [= string] The ToolTipText property syntax has these parts: Part object string Description An object expression that evaluates to an object in the Applies To list. A string associated with an object in the Applies To list. that appears in a small rectangle below the object when the user's cursor hovers over the object at run time for about one second.
With Statement Executes a series of statements on a single object or a user-defined type. Syntax With object [statements] End With The With statement syntax has these parts: Part object statements Description Required. Name of an object or a user-defined type. Optional. One or more statements to be executed on object.
Remarks The With statement allows you to perform a series of statements on a specified object without requalifying the name of the object. For example, to change a number of different properties on a single object, place the property assignment statements within the With control structure, referring to the object once instead of referring to it with each property assignment. The following example illustrates use of the With statement to assign values to several properties of the same object. With MyLabel .Height = 2000 .Width = 2000 .Caption = "This is MyLabel" End With Note Once a With block is entered, object can't be changed. As a result, you can't use a single With statement to affect a number of different objects. Concatenating Strings: Used to force string concatenation of two expressions. Syntax
Example: txtOutPut.Text= Welcome & To VB 6 txtName.Text= txtFirstName.Text & & txtLastName.Text Remarks If an expression is not a string, it is converted to a String variant. The data type of result is String if both expressions are string expressions; otherwise, result is a String variant. If both expressions are Null, result is Null. However, if only one expression is Null, that expression is treated as a zero-length string ("") when concatenated with the other expression. Any expression that is Empty is also treated as a zero-length string.
2. String Use to store alphanumeric values. A variable length string can store approximately 4 billion characters 3. Date Use to store date and time values. A variable declared as date type can store both date and time values and it can store date values 01/01/0100 up to 12/31/9999 4. Boolean Boolean data types hold either a true or false value. These are not stored as numeric values and cannot be used as such. Values are internally stored as -1 (True) and 0 (False) and any non-zero value is considered as true. Naming rules and convention in VB 6.0 These are the rules to follow when naming elements in VB - variables, constants, controls, procedures, and so on:
Relational Operators Operators > < >= Description Greater than Less than Example 10>8 10>8 Result True False True
Logical Operators Operators OR AND Description Operation will be true if either of the operands is true Operation will be true only if both the operands are true
Val Function A function performs an action and returns a Value. The Expression to operate upon, called the arguments, must be enclosed in parenthesis. The Val function converts text data into a numeric value. General form: Val(ExpressionToConvert) The expression can be the property of a control, a variable or a constant. A function cannot stand by itself. It returns a value that can be part of a statement, such as the assignment statements. Example: intQuantity=Val(txtQuantity.Text) curPrice=Val(txtPrice.Text) Important: When the Val function converts an argument to numeric, it begins at the arguments left most character. If that character is a numeric digit, decimal point, or sign, It converts the character to numeric and moves to the next character. As soon as a nonnumeric character is found, the operation stops. Example: Argument (blank) 123.45 $100 1,000 A123 123A 4C5 -123 +123 12.45.2 Numeric Value Returned by the Val Function 0 123.45 0 1 0 123 4 -123 123 12.45
Code: Private Sub cmdAdd_Click() txtOutput.Text = Val(txtNum1.Text) + Val(txtNum2.Text) End Sub Private Sub cmdDifference_Click() txtOutput.Text = Val(txtNum1.Text) - Val(txtNum2.Text) End Sub Private Sub cmdMultiply_Click() txtOutput.Text = Val(txtNum1.Text) * Val(txtNum2.Text) End Sub Private Sub Command4_Click() txtOutput.Text = Val(txtNum1.Text) / Val(txtNum2.Text) End Sub
FORMATTING DATA Use the formatting functions to format the data. To format means to control the way the output look. For example, 12 is just a number but $12.00 conveys more meaning for dollar amount. VB 6 introduces 4 new formatting functions 1. FormatCurrency FormatCurrency Returns an expression formatted as a number with a leading currency symbol ($) Simple Form FormatCurrency (Expression) General Form FormatCurrency (Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]]) 2. FormatNumber FormatNumber Returns an expression formatted as a number
For the examples below, assume dblTestNumber contains the value 12345.678 Expression FormatNumber(dblTestNumber, 2, True, True, True) FormatCurrency(dblTestNumber, 2, True, True, True) FormatPrecent(dblTestNumber, 2, True, True, True) "Try It" Code: Private Sub cmdTryIt_Click() Dim dblTestNumber As Double dblTestNumber = Val(InputBox("Please enter a number:")) Print "Input: "; Tab(25); dblTestNumber Print "Using FormatNumber:"; Tab(25); FormatNumber(dblTestNumber, 2, True, True, True) Print "Using FormatCurrency:"; Tab(25); FormatCurrency(dblTestNumber, 2, True, True, True) Print "Using FormatPercent:"; Tab(25); FormatPercent(dblTestNumber, 2, True, True, True) End Sub Output: Result 12,345.68 $12,345.68 1,234,567.80%
4. FormatDateTime FormatDateTime Returns an expression formatted as a date or time. Syntax: FormatDateTime(Date[,NamedFormat]) The FormatDateTime function syntax has these parts: Part Date NamedFormat Description Required. Date expression to be formatted. Optional. Numeric value that indicates the date/time format used. If omitted, vbGeneralDate is used.
Settings: The NamedFormat argument has the following settings: Constant Value Description vbGeneralDate 0 Display a date and/or time. If there is a date part, display it as a short date. If there is a time part, display it as a long time. If present, both parts are displayed.