Learn the most popular programming language of the most popular Operating System: Windows

Ad

Opening the Properties Window and Changing Form Properties

Besides a Project Explorer window, each form (or control) contains a Properties window.  As stated in Running a Visual Basic Program, a property is a named attribute of an object.  Properties are used to change the appearance or behavior of objects.

Figure 2.6 illustrates the default Properties dialog box for a form.  If this box is not visible, you can bring it into view by pressing the F4 function key, or choosing View, Properties Window.  With the form having the focus, press your right mouse button and drag down the Properties list.

Figure 2.6  
The Properties dialog box of a form contains the built-in form attributes that you can change.

Over 50 properties can be set for a form.  Although this number seems overwhelming at first, some properties are used so frequently that they represent an initial set to remember.

Form Properties

Caption

Name

BorderStyle

MinButton

MaxButton

ControlBox

WindowSize

BackColor

FontName

FontSize

FontBold

FontItalic

FontStrikethru

FontUnderline

ForeColor

StartUpPosition

To simplify this list somewhat, the items can be grouped by their uses:

  • Seven properties deal with the way in which the form or text appears on the display screen (Caption, BorderStyle, MinButton, MaxButton, ControlBox, WindowSize and StartUpPosition).
  • The identification of an object is specified by the Name property.
  • Font settings are controlled using the Fonts dialog box (FontName, FontSize, FontBold, FontItalic and FontStrikethru).
  • Color settings (ForeColor and BackColor) use a special palette.

There are three ways to change most property settings:

  • Click the property to highlight it, and enter (type in text) the new property setting in the text box.
  • Double-click the setting to view the alternative settings.
  • Click the down arrow to open the drop-down menu for property settings.

Properties for fonts and color launch a separate dialog box for you to enter settings.

Changing a Caption

The Caption property enables you to change the title that appears on the top of a form.  Instead of Form1, use the Caption property to add a title.  To change the caption, select Caption in the Properties dialog box and type the new title in the text box next to the property name.

Changing a Form Name

The Name property specifies the name of the form to be used in writing Visual Basic code. Remember the following rule: The name, not the caption, is the identifier.  When writing coded instructions, the Name property appears as the object name.  To change the name, select Name in the Properties dialog box and type the new name.

Changing the Border Style

The BorderStyle property enables you to change the appearance of the form’s border.  To change the border setting, double-click the current setting to reveal other choices, or click the down arrow to open the drop-down list of the six options.

If you are uncertain about the six border choices and their precise effects, click BorderStyle to give it the focus in the Properties dialog box, and press F1 (the Help function key).  Visual Basic Help displays the six style choices and explains their effects, as shown in Table 2.2.

Table 2.2 The Settings for the BorderStyle Property
Setting Style Description
0 None No border or border-related elements.
1 Fixed Single Can include Control menu icon, title bar, Maximize button, and Minimize button.  Resizable only using Maximize and Minimize buttons.
2 Sizable The default.  The size can be changed using any of the optional border elements listed for setting 1.
3 Fixed Dialog Can include Control menu icon and title bar; can’t include Maxiimize or Minimize buttons.  Not resizable.
4 FixedToolWindow Under 16-bit versions of Windows and Windows NT 3.51 and earlier, behaves like Fixed Single.  Does not display Maximize or Minimize buttons.  Not resizable.  Under Windows 95, displays the Close button and displays the title bar text in a reduced font size.  The form does not appear in the Windows 95 taskbar.
5 SizableToolWindow Under 16-bit version of Windows and Windows NT 3.5 and earlier, behaves like sizable.  Docs not display Maximize or Minimize buttons, Resizable.  Under Windows 95, displays the Close button and displays the title bar text in a reduced font size.  The form does not appear in the Windows 95 taskbar.

The online Help is one of Visual Basic’s strongest features.  Remember, the F1 key is your friend!  Use it often.  The language is just too vast to remember all of it.

Share:

The concept of Focus

The concept of focus is important in Visual Basic.  The object that is selected (such as a form, control, or menu bar selection) is said to have focus.  In order for Visual Basic to know what file to save, it is necessary to click the object to give it focus, making it the active object.  Likewise, to remove a file, the object must be given focus.  To remove a file, open the Project window, click the file to remove, and choose File, Remove and the name of the file to remove will also appear.  An alternative is to display the Project Explorer, click the file that you want to delete, and right-click to produce the shortcut menu shown in Figure 2.3.  We discuss the concept of focus at length later.  There are even unique events, such as Gotfocus and LostFocus, that deal with this issue.

Figure 2.3 Display the Project Explorer and right-click to reveal several file optiions, including a command for removing a file from a project.

Exercise 2.2  Using the Remove and Add Commands

This exercise assumes that you completed Exercise 2.1 and saved the form as F2-1.frm.

  1. Open a new Standard EXE project, and change the name of the project to Project2_2 (click Project, Project1 Properties).
  2. Choose Project, Remove Form1.Form1 must have the focus because it is the only object assigned to the project.
  3. Choose Project, Add File.  Navigate through Windows to the location where you saved F2-1.frm, and add this form to your Project (see Figure 2.4).

    Figure 2.4

    The Add File dialog box lists saved forms that can be added to a project.

  4. Open the Project Explorer Window, and give form F2-1.frm the focus.
  5. Choose File, Save File As (or click the right mouse button).  When the dialog box opens, navigate to the location where you want to save the file, and name it F2-2.frm.
  6. Open the Project Window again and observe what happens.  The name of the form has been changed and assigned to the new project.
  7. Choose File, Save Project As.  In this instance, you are not asked to name the form because it has already been named and saved.  Instead, you are asked only to name the project, which we named P2-2.vbp.

Other File Menu Commands

Besides the four Project menu commands and the two file commands found on the File menu, the latter also contains the Print and Print Setup commands and the Make Project1.Exe commands, as follows:

  • Print – Choose File, Print to display several options for printing information about a project (see Figure 2.5).  You can print the form image, code, or the form as text, and you can choose to print information for a module or for the entire project.
  • Print Setup – Choose File, Print Setup to launch the standard Windows Print Setup dialog box.
  • Make Project1.Exe – Choose File, Make Project.Exe to create an executable application.  Project modules are compiled into a single .EXE file.  This file is either a P-Code interpreted executable or a native code executable file.  (The two code formats are explained in “Interpreted P-Code,” and “Compiled Native Code,” later.)

Both types of executables require runtime files.  The Visual Basic Setup Wizard can help you determine which runtime file your application requires.

Figure 2.5 The Print-Project dialog box enables you to choose the parts of an application that you want to print.

Exercise 2.3  Using the Print Command

This exercise is designed to show you the type of information printed for a project.

  1. Open a new Standard EXE project.
  2. Choose File, Print.
  3. When the dialog box appears, click Current Project, Form Image, Code and Form as Text.
  4. Click OK.

What is the difference between the Form Image and the Form as Text choice!  Why is there no computer code?

Share:

Naming a Project

Each time you begin a new project, the default name, Project1, appears at top of the form.  Unless you change the name, every project you work on will be named Project1.  To change the name, choose Project, Project1 Properties (see Figure 2.2), and type a new project name.  For example, you might enter Project2_1 for this initial project.

Figure 2.2

The Project Properties dialog box is used to change the name of the project from the default, Project1, to a name of your choosing.

Exercise 2.1 Using the Save Project As Command

This exercise asks you to do very little, but it does introduce you to the file naming conventions. Start Visual Basic, and perform the following steps:

  1. Open a Standard EXE new project.
  2. Choose Project, Project1 Properties and change the name of the project to Project2_1. Click OK. This new name should appear on the topmost title bar of Visual Basic.
  3. Choose File, Save Project As. A dialog box appears and asks if you want to save the file as Form1.frm. If you click Cancel, the form is not saved and you have to rebuild it if you need it. Imagine that you spent an hour perfecting a form. Unless you save it, your work will be lost.
  4. Before you click Save, navigate to the location where you want to save the file, and assign a name to the form. Assign a unique name - something other than the default, Form1.frm. You can use the notation F2-1.frm to indicate that this form goes with exercise 2.1 (not very clever, but it works). A more descriptive name would be better.

    If you want to store the form on a diskette placed in the a: drive of the computer, navigate to the drive and type F2-1.frm.

  5. After the form has been saved, a second dialog box appears asking you to assign a name to the project. Again, assign a unique name (not the default, Project1.VBP). You can call it P2-1.VBP to indicate that this project goes with Exercise 2.1. Here too, a descriptive project name would be better.

If you want to save the project on a diskette placed in the a: drive of the computer, navigate to the drive and type P2-1.VBP

The Add File and Remove File Commands

Files can be added to, or removed from, the .VBP project file using the file commands contained on the Project menu. When adding or removing files, keep in mind that you are adding or removing files from a project. The following are two Project menu commands that you will use often in this book:

  • Add File - Choose Project, Add File to open a dialog box (see Figure 2.4) that enables you to navigate the Windows file directory to identify a previously saved file and to add the file to a project, for example, an .FRM (form), .BAS (coded module), .CLS (class modules), or .RES (resource file). This command is especially important when you use a file built for a different project. Simply identify the file name, and click OK.
  • Remove <Name of File> - Choose Project, Remove <Name of File> to remove the file from the current Project that is active (has the focus, a term that is described next).

Other Project menu file commands include Add Form, Add MDI Form, Add Module, and Add Class Module. These enable you to add new types of forms and modules to a project.

The Save File and Save File As Commands

The following are two File menu commands that are used to save a particular file rather than an entire project:

  • Save File - Choose File, Save File to save the form or module that is active (has the focus). If the file has previously been saved, this command updates the file. If the file is new, this command prompts you for the name of the file and, once entered, adds the file to a project when the project file (.VBP file) is next saved.
  • Save File As - Choose File, Save File As to save the current file to a disk. This option always prompts you for the file name. Like the File, Save Project As command, File, Save File As is used to save a file for the first time or to save a copy of an existing file.

You will find file commands most useful when you want to use the same forms and modules in different projects.  There is nothing to prohibit you from using the same form in dozens of projects because each form is saved as a separate file.

Share:

Learning How to Manage Visual Basic Projects

In this section, you learn how to open and save a project, add and delete files from the Project window, give an object focus (further explained in later section “The Concept of Focus”), and use the other File commands provided with Visual Basic.  You will also work through several exercises to rest your knowledge of the concepts presented.

Opening, Saving, Adding and Removing Projects

Whenever you open Visual Basic, you always start a new project.  However, there are File commands that enable you to work with both old and new projects, and File and Project commands for working with old and new files.  The File menu on the menu bar contains six commands designed for managing projects, as follows:

  • New Projects – Choose File, New Project to start a new project.  If you are working on a project, this command prompts you to save the current project.  It then closes the current project to enable you to start a new one.
  • Open Project -  Choose File, Open Project to open a saved project.  Before opening a project, this command asks if you want to save a current project if one exists.
  • Add Project – Choose File, Add Project to open a saved project and add it to another, provided one exists.  A Visual Basic application can contain any number of projects.
  • Remove Project – Choose File, Remove Project to remove the selected project from a project group.
  • Save Project As – Choose File, Save Project As to save the current project to a disk.  This option always prompts you for a project name.  Use this command to save a project for the first time or save a copy of an existing project.  When first saving a project, you are asked whether or not you want to save each form and module associated with a project.

    For each form or module, you can assign a name.  You should name each form with a name other than the default name (such as form1.frm and form2.frm); otherwise, you will design over the form when you start a new project and find it impossible to retrieve the form you thought you had saved.  You should also name each project with a unique name, or else Visual Basic will assign every project the same default name.

  • Save Project – Choose File, Save Project to save the current project to a disk.  this option saves all forms and modules as separate files.  It creates a file with .VBP (Visual Basic Project) extension.  If the project is being saved for the first time, this command prompts you for the project name.  If saved earlier, it updates the .VBP file.

The .VBP file is saved as text or in ANSI (American National Standards Institute) format.  This allows you to inspect its contents with any text editor.  Each project contains one – and only one - .VBP file, which provides a description of the project, showing the names of the stored files and other descriptive information.

Share:

Understanding the Concept of a Visual Basic Project

Every Visual Basic application is defined and saved as a project.  Each project, in turn, consists of a collection of files.  These files can include modules, insertable objects, and a single resource file.  Projects themselves are tracked by a project file, which has a .VBP extension.

Form modules, as discussed earlier are first seen as a windows with a caption, but little else.  From modules contain coded instructions called procedures for the form itself and for the controls and insertable objects placed on the form.  Other modules include standard modules and class modules.  You will learn the differences among these types of modules as you progress.

The tools of the toolbox represent controls and insertable objects.  The toolbox can be made visible or invisible by choosing View, Toolbox.  When visible, the toolbox contains a set of icons – each representing a standard or a custom control.  A Visual Basic project always includes a set of standard controls and can also include custom controls.  Each custom control has an .OCX extension.  In this section you are asked to write some beginning Visual Baisc procedures for forms.  In “Adding Controls and Event Procedures to Form Modules,” you will add procedures for stand controls.

Projects can also include a resource file, which can contain either binary data, such as images and sounds, or string data.  Resource files need to be created by a Windows resource compiler (typically a C or C++ language compiler), or you can use the resource compiler bundled with Visual Basic.

The Files that Make Up a Stanbdard EXE Project

In working with Visual Basic, you are asked to work with different types of files.  Each file type is given a unique file extension, which enables you to identify it.  Visual Basic contains over two dozen types of files, each of which has a different extension.  The Table below shows eight common file types contained within a project, their extensions, and their meanings.

Table 2.1 Common File Types
Type of File Extension Extension
Standard Module .BAS Each coded module is saved as a file
Class Module .CLS Each class module is saved as a file
Form Module .FRM Each form is saved as a file
Binary .FRX Each Icon or Picture property value is saved by Visual Basic in .FRX form
Log .LOG A file for logging load errors.
Resource .RES A project can have a single resource file for storing binary and string data
Project .VBP Each project is saved as a file.
Workspace .VBW Each workspace for a project is saved as a file.

This file notation is used throughout.  When you save a form, it is saved with a .FRM extension, and all event procedures written for that form are also saved in the .FRM file.  Because procedures are not saved as separate files with their own unique extension, they become bound to forms.  When you write and save a coded standard module, it is saved with a .BAS extension.  Coded modules are thus different from event procedures written for forms.  Coded modules are not bound to forms.

The Project Window (Project Explorer) in the Visual Basic Design Environment

Whenever you begin a Visual Basic program, you begin a new project.  Each project can contain several forms, several standard and class coded modules, and custom controls.  The Project window displays a list of all modules assigned to a project.  Whenever you begin a new project, a default Project window is created (see Fiigure 2.1) .  If the window fails to appear or is hidden, choose View, Project Explorer; press Ctrl+R; or click the Project Explorer icon.  In addition, your environment can be set to remove the docking of the Project Explorer.  This setting is controlled by choosing Tools, Options, clicking the Docking tab, and turning off the Project Explorer and Object browser selections.

Figure 2.1: This Project window reveals that Project1 contains a forms folder that is limited to a single form.

Figure 2.1 illustrates a Project window that contains three small icons on the left-hand side.  The leftmost icon enables you to view code, while the middle one enables you to view the underlying object (which in this case is the form).  Forms, the third icon, is important when projects become large and contain several forms or when projects are combined.  With large projects, all forms are placed in one folder, and all modules are placed in a second.  Toggling forms enables you to show or hide all forms for a project that are contained in the Forms folder.

Share:

Writing and Running first Visual Basic Program

Last week you have learned how to run a program that had been made for you.  You probably noticed that when working with Visual Basic, several types of windows could be inspected – even though you were not asked to examine any one window in detail.  Here, you learn about three types of windows:

  • Project window
  • Properties window
  • Code window

You will learn how to move from one window to the next in writing a Visual Basic program.  Also, you will write and run several simple Visual Basic programs.

In working through the next few exercises you will master a number of new tasks, including how to

  • open a new project;
  • save a project;
  • name a form and project;
  • remove a form from a project;
  • add a form to a project;
  • print a form, form text, and code;
  • write a click() procedure;
  • write a KeyPress() procedure;
  • change font size, style and type;
  • change the window state.

Objectives

The tasks for this chapter are distilled into five objectives that teach you the fundamentals of writing and running a Visual Basic program, as follows:

  1. Understanding the concept of a Visual Basic project
  2. Learning how to manage Visual Basic projects
  3. Opening the Properties window and changing form properties
  4. Opening the Code window and writing Visual Basic instructions
  5. Producing a compiled application from a Standard EXE project

Understanding the Concept of a Visual Basic Project

Every Visual Basic application is defined and saved as a project.  Each project, in turn, consists of a collection of files.  These files can include modules, insertable objects, and a single resource file.  Projects themselves are tracked by a project file, which has a .VBP extension.

Form modules, as discussed earlier are first seen as windows with a caption, but Form modules contain coded instructions called procedures for the form itself and for the controls and insertable objects placed on the form.  Other modules include standard modules and class modules.  You will learn the differences among these types of modules as you progress.

The tools of the toolbox represent controls and inserteable objects.  The toolbox can be made visible or invisible by choosing View, Toolbox.  When visible, the toolbox contains a set of icons – each representing a standard or a custom control.  A visual Basic project always includes a set of standard controls and can also include custom controls.  Each custom control has an .OCX extension.  You will be asked to write some beginning Visual Basic procedures for forms.  In “Adding Controls and Event Procedures to Form MOdules, you will add procedures for standard controls.

Projects can also include a resource file, which can contain either binary data, such as images and sounds, or string data.  Resource files need to be created by a Windows resource compiler (typically a C or C++ language compiler), or you can use the resource compiler bundled with Visual Basic.

Share:

Running Visual Basic Applications

Now that you are a bit more familiar with the Visual Basic design environment, let us run few Visual Basic Applications.

Exercise 1.3  Running the Finance Calculator Demo

  1. Create a Folder with the name Finance on your Hard Drive. Copy the Finance Project Source Code, Paste them into Notepad and save them into the Finance folder with the Filename and extension specified:

    Project File: Finance.vbp

    Type=Exe
    Form=Form1.frm
    Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\WINDOWS\system32\stdole2.tlb#OLE Automation
    IconForm="Form1"
    Startup="Form1"
    Command32=""
    Name="Project1"
    HelpContextID="0"
    CompatibleMode="0"
    MajorVer=1
    MinorVer=0
    RevisionVer=0
    AutoIncrementVer=0
    ServerSupportFiles=0
    VersionCompanyName="Home"
    CompilationType=0
    OptimizationType=0
    FavorPentiumPro(tm)=0
    CodeViewDebugInfo=0
    NoAliasing=0
    BoundsCheck=0
    OverflowCheck=0
    FlPointCheck=0
    FDIVCheck=0
    UnroundedFP=0
    StartMode=0
    Unattended=0
    ThreadPerObject=0
    MaxNumberOfThreads=1
    
    [MS Transaction Server]
    AutoRefresh=1
    

    Project File: Finance.vbw

    Form1 = 138, 622, 585, 947, C, 0, 0, 0, 0, 
    

    Project File: Form1.frm

    VERSION 5.00
    Begin VB.Form Form1 
       Caption         =   "New House Payment"
       ClientHeight    =   4665
       ClientLeft      =   5565
       ClientTop       =   2115
       ClientWidth     =   6315
       LinkTopic       =   "Form1"
       ScaleHeight     =   4665
       ScaleWidth      =   6315
       Begin VB.CommandButton cmdCompute 
          Caption         =   "Compute it"
          Height          =   495
          Left            =   1440
          TabIndex        =   3
          Top             =   3840
          Width           =   2175
       End
       Begin VB.TextBox txtYears 
          Height          =   495
          Left            =   3480
          TabIndex        =   2
          Top             =   1800
          Width           =   1815
       End
       Begin VB.TextBox txtRate 
          Height          =   495
          Left            =   3480
          TabIndex        =   1
          Top             =   960
          Width           =   1815
       End
       Begin VB.TextBox txtBorrow 
          Height          =   495
          Left            =   3480
          TabIndex        =   0
          Top             =   240
          Width           =   1815
       End
       Begin VB.Label Label4 
          Caption         =   "Monthly Payments"
          Height          =   495
          Left            =   480
          TabIndex        =   8
          Top             =   2640
          Width           =   2655
       End
       Begin VB.Label Label3 
          Caption         =   "Life of Loan (in years)"
          Height          =   495
          Left            =   480
          TabIndex        =   7
          Top             =   1800
          Width           =   2655
       End
       Begin VB.Label Label2 
          Caption         =   "Yearly interest rate (i.e. 6.5)"
          Height          =   495
          Left            =   480
          TabIndex        =   6
          Top             =   960
          Width           =   2655
       End
       Begin VB.Label Label1 
          Caption         =   "Borrow"
          Height          =   495
          Left            =   480
          TabIndex        =   5
          Top             =   240
          Width           =   2655
       End
       Begin VB.Label lblPayment 
          BorderStyle     =   1  'Fixed Single
          Height          =   495
          Left            =   3480
          TabIndex        =   4
          Top             =   2640
          Width           =   1815
       End
    End
    Attribute VB_Name = "Form1"
    Attribute VB_GlobalNameSpace = False
    Attribute VB_Creatable = False
    Attribute VB_PredeclaredId = True
    Attribute VB_Exposed = False
    Private Sub cmdCompute_Click()
    Dim yearIRate As Single
    Dim nperiod As Integer
    Dim borrow As Currency
    Dim payment As Currency
    
    yearIRate = CSng(txtRate.Text) / (12 * 100)
    nperiod = CInt(txtYears.Text) * 12
    borrow = CCur(txtBorrow.Text)
    
    payment = Pmt(yearIRate, nperiod, -borrow, 0, 0)
    lblPayment.Caption = Format(payment, "Currency")
    
    End Sub
    
  2. Start Visual Basic from Windows.
  3. Select Open Project from File Menu. If a dialog box appears asking you to save a file, click No.
  4. Browse to the Finance folder, where you have saved Finance Project files and select Finance.vbp File and click the Open button.
  5. Choose Run, Start from the Visual Basic menu, or press F5. This runs the Visual Basic application.
  6. Enter Value 100,000 into the Text Control with the label borrow
  7. Enter Value 7.5 into the Text control with the label Yearly Interest Rate.
  8. Enter Value 30 into the Text control with the label Life of loan.
  9. Click on the Command Button to Calculate and display the Monthly Payments.
  10. Choose Options, Exit to exit the application and return to the Visual Basic design environment.
  11. Choose File, Remove Project to remove the Project from the design environment.

Exercise 1.4  Running the Highest and Lowest Score Values Demo

  1. Create a Folder with the name Score on your Hard Drive. Copy the Score Project Source Code, Paste them into Notepad and save them into the Score folder with the Filename and extension specified:

    Project File: HighLow.vbp

    Type=Exe
    Form=Form1.frm
    Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\WINDOWS\system32\stdole2.tlb#OLE Automation
    IconForm="Form1"
    Startup="Form1"
    Command32=""
    Name="Project1"
    HelpContextID="0"
    CompatibleMode="0"
    MajorVer=1
    MinorVer=0
    RevisionVer=0
    AutoIncrementVer=0
    ServerSupportFiles=0
    VersionCompanyName="Home"
    CompilationType=0
    OptimizationType=0
    FavorPentiumPro(tm)=0
    CodeViewDebugInfo=0
    NoAliasing=0
    BoundsCheck=0
    OverflowCheck=0
    FlPointCheck=0
    FDIVCheck=0
    UnroundedFP=0
    StartMode=0
    Unattended=0
    ThreadPerObject=0
    MaxNumberOfThreads=1
    
    [MS Transaction Server]
    AutoRefresh=1
    
    

    Project File: HighLow.vbw

    Form1 = 648, 202, 1253, 947, I, 0, 0, 0, 0, 
    

    Project File: Form1.frm

    VERSION 5.00
    Begin VB.Form Form1 
       Caption         =   "Get Score"
       ClientHeight    =   3765
       ClientLeft      =   5385
       ClientTop       =   2310
       ClientWidth     =   7785
       LinkTopic       =   "Form1"
       ScaleHeight     =   3765
       ScaleWidth      =   7785
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   1
          Left            =   1080
          TabIndex        =   0
          Top             =   240
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   2
          Left            =   2400
          TabIndex        =   1
          Top             =   240
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   3
          Left            =   3720
          TabIndex        =   2
          Top             =   240
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   4
          Left            =   5040
          TabIndex        =   3
          Top             =   240
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   5
          Left            =   6360
          TabIndex        =   4
          Top             =   240
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   14
          Left            =   5040
          TabIndex        =   13
          Top             =   1440
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   13
          Left            =   3720
          TabIndex        =   12
          Top             =   1440
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   12
          Left            =   2400
          TabIndex        =   11
          Top             =   1440
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   11
          Left            =   1080
          TabIndex        =   10
          Top             =   1440
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   10
          Left            =   6360
          TabIndex        =   9
          Top             =   840
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   9
          Left            =   5040
          TabIndex        =   8
          Top             =   840
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   8
          Left            =   3720
          TabIndex        =   7
          Top             =   840
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   7
          Left            =   2400
          TabIndex        =   6
          Top             =   840
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   6
          Left            =   1080
          TabIndex        =   5
          Top             =   840
          Width           =   1215
       End
       Begin VB.CommandButton cmdScores 
          Caption         =   "Set High and Low Scores"
          Height          =   495
          Left            =   600
          TabIndex        =   15
          Top             =   2880
          Width           =   2655
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   0
          Left            =   6360
          TabIndex        =   14
          Top             =   1440
          Width           =   1215
       End
       Begin VB.Label Label5 
          Caption         =   "Team 3"
          Height          =   495
          Left            =   120
          TabIndex        =   22
          Top             =   1440
          Width           =   855
       End
       Begin VB.Label Label4 
          Caption         =   "Team 1"
          Height          =   495
          Left            =   120
          TabIndex        =   21
          Top             =   240
          Width           =   855
       End
       Begin VB.Label Label3 
          Caption         =   "Team 2"
          Height          =   495
          Left            =   120
          TabIndex        =   20
          Top             =   840
          Width           =   855
       End
       Begin VB.Label lblLow 
          BorderStyle     =   1  'Fixed Single
          Height          =   495
          Left            =   5640
          TabIndex        =   19
          Top             =   2880
          Width           =   1935
       End
       Begin VB.Label lblHigh 
          BorderStyle     =   1  'Fixed Single
          Height          =   495
          Left            =   5640
          TabIndex        =   18
          Top             =   2280
          Width           =   1935
       End
       Begin VB.Label Label2 
          Caption         =   "Low Score is"
          Height          =   495
          Left            =   3600
          TabIndex        =   17
          Top             =   3000
          Width           =   1815
       End
       Begin VB.Label Label1 
          Caption         =   "High Score is"
          Height          =   495
          Left            =   3600
          TabIndex        =   16
          Top             =   2400
          Width           =   1815
       End
    End
    Attribute VB_Name = "Form1"
    Attribute VB_GlobalNameSpace = False
    Attribute VB_Creatable = False
    Attribute VB_PredeclaredId = True
    Attribute VB_Exposed = False
    Private Sub cmdScores_Click()
    Static score(0 To 14) As Integer
    Dim num As Integer
    Dim High As Integer
    Dim Low As Integer
    For num = 0 To 14
      score(num) = Val(txtScore(num).Text)
    Next num
       High = High_Score(score(), num - 1)
       lblHigh.Caption = Str$(High)
       Low = Low_Score(score(), num - 1)
       lblLow.Caption = Str$(Low)
    End Sub
    
    Private Function High_Score(score() As Integer, num As Integer)
    Dim max As Integer
    Dim High As Integer
    High = 0
    For max = 0 To num
       If (score(max) > High) Then
           High = score(max)
       End If
    Next max
    High_Score = High
      
    End Function
    
    Private Function Low_Score(score() As Integer, num As Integer)
    Dim min As Integer
    Dim Low As Integer
    Low = 1000
    For min = 0 To num
       If (score(min) < Low) Then
           Low = score(min)
       End If
    Next min
    Low_Score = Low
      
    End Function
    
    
  2. Start Visual Basic from Windows.
  3. Select Open Project from File Menu. If a dialog box appears asking you to save a file, click No.
  4. Browse to the Score folder, where you have saved the Score Project files, and select HighLow.vbp File and click the Open button.
  5. Choose Run, Start from the Visual Basic menu, or press F5. This runs the Visual Basic application.
  6. Enter some random numbers into the 15 Text Boxes given with the labels Team 1, Team 2 and Team 3.
  7. Click on the Command Button to find the Highest and Lowest score values and display them.
  8. Choose Options, Exit to exit the application and return to the Visual Basic design environment.
  9. Choose File, Remove Project to remove the Project from the design environment.

Exercise 1.5  Running the Race Pace Demo

  1. Create a Folder with the name Race on your Hard Drive. Copy the Race Project Source Code, Paste them into Notepad and save them into the Score folder with the Filename and extension specified:

    Project File: Race.vbp

    Type=Exe
    Form=..\Highlow\Race\Form1.frm
    Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\WINDOWS\system32\stdole2.tlb#OLE Automation
    Startup="Form1"
    Command32=""
    Name="Project1"
    HelpContextID="0"
    CompatibleMode="0"
    MajorVer=1
    MinorVer=0
    RevisionVer=0
    AutoIncrementVer=0
    ServerSupportFiles=0
    VersionCompanyName="Home"
    CompilationType=0
    OptimizationType=0
    FavorPentiumPro(tm)=0
    CodeViewDebugInfo=0
    NoAliasing=0
    BoundsCheck=0
    OverflowCheck=0
    FlPointCheck=0
    FDIVCheck=0
    UnroundedFP=0
    StartMode=0
    Unattended=0
    ThreadPerObject=0
    MaxNumberOfThreads=1
    
    [MS Transaction Server]
    AutoRefresh=1
    
    

    Project File: Race.vbw

    Form1 = 136, 117, 583, 940, , 0, 0, 0, 0, 
    

    Project File: Form1.frm

    VERSION 5.00
    Begin VB.Form Form1 
       Caption         =   "Convert Race Result"
       ClientHeight    =   4155
       ClientLeft      =   2040
       ClientTop       =   1890
       ClientWidth     =   6585
       LinkTopic       =   "Form1"
       ScaleHeight     =   4155
       ScaleWidth      =   6585
       Begin VB.CommandButton cmdClear 
          Caption         =   "Clear"
          Height          =   495
          Left            =   840
          TabIndex        =   7
          Top             =   3240
          Width           =   1575
       End
       Begin VB.TextBox txtTime 
          Height          =   495
          Left            =   4680
          TabIndex        =   3
          Top             =   720
          Width           =   1575
       End
       Begin VB.Frame Frame1 
          Caption         =   "Click on one"
          Height          =   2175
          Left            =   480
          TabIndex        =   0
          Top             =   600
          Width           =   2415
          Begin VB.OptionButton Opt8K 
             Caption         =   "8 K Run/Walk"
             Height          =   255
             Left            =   360
             TabIndex        =   2
             Top             =   1440
             Width           =   1815
          End
          Begin VB.OptionButton Opt10K 
             Caption         =   "10 K Run/Walk"
             Height          =   255
             Left            =   360
             TabIndex        =   1
             Top             =   720
             Width           =   1815
          End
       End
       Begin VB.Label Label3 
          Caption         =   "Pace [in minutes per mile]"
          Height          =   855
          Left            =   3000
          TabIndex        =   6
          Top             =   1800
          Width           =   1335
       End
       Begin VB.Label lblPace 
          Height          =   495
          Left            =   4680
          TabIndex        =   5
          Top             =   1920
          Width           =   1575
       End
       Begin VB.Label Label1 
          Caption         =   "Enter Time in Minutes [i.e. 50.5] and press Enter"
          Height          =   855
          Left            =   3000
          TabIndex        =   4
          Top             =   720
          Width           =   1335
       End
    End
    Attribute VB_Name = "Form1"
    Attribute VB_GlobalNameSpace = False
    Attribute VB_Creatable = False
    Attribute VB_PredeclaredId = True
    Attribute VB_Exposed = False
    
    
    Private Sub cmdClear_Click()
       lblPace.Caption = ""
       txtTime.Text = ""
       txtTime.SetFocus
    End Sub
    
    Private Sub txtTime_KeyPress(KeyAscii As Integer)
    Dim result As Single
    Dim newtime As Single
    
       If KeyAscii = vbKeyReturn Then
          newtime = CSng(txtTime.Text)
          result = mph(newtime)
          lblPace.Caption = Str$(result)
       Else
          Exit Sub
       End If
    
    End Sub
    
    
    Function mph(newtime As Single) As Single
       If (Opt10K = True And newtime > 0) Then
          mph = CSng(newtime / 6.2)
       ElseIf (Opt8K = True And newtime > 0) Then
          mph = CSng(newtime / 5.1)
       End If
       txtTime.SetFocus
    
    End Function
    
  2. Start Visual Basic from Windows.
  3. Select Open Project from File Menu. If a dialog box appears asking you to save a file, click No.
  4. Browse to the Race folder, where you have saved the Race Project Files and select Race.vbp File and click Open button.
  5. Choose Run, Start from the Visual Basic menu, or press F5. This runs the Visual Basic application.
  6. Click on one of the Option Buttons to select it.
  7. Enter the value 48.45 into the Text Box.
  8. Press Enter key to calculate the pace of race in miles required per minute and display it in the label below the Text Box.
  9. Click on the Command Button to clear the values and try it on a different set of values
  10. Choose Options, Exit to exit the application and return to the Visual Basic design environment.
  11. Choose File, Remove Project to remove the Project from the design environment.

We will learn how to design these Forms and programs at a later stage.

Technorati Tags: ,,
Share:

Running Sample Visual Basic Programs

Given this brief introduction to Visual Basic, it is time for you to become more familiar with the Visual Basic programming environment.  Still, you are not expected to write a Visual Basic program at this time; right now, you’ll start Visual Basic and become a bit more familiar with the way in which the environment can be configured.

A Quick Tour of the Visual Basic Design Environment.

The Visual Basic design environment is almost infinitely configurable.  This makes it difficult to describe a standard Visual Basic user interface.  It depends upon the way the design environment was last configured.

There are two overall design environment choices: MDI or SDI.  The abbreviation MDI stands for multiple-document interface, and it is the default Visual Basic setting.  It features an overall container window and movable and dockable windows inside the container.  It is the environment shown under the topic Low-Visual and High-Visual Languages.  The abbreviation SDI stands for single-document interface.  It features free-floating windows on the Windows desktop, which is the environment that would be most familiar to you if you have worked with previous versions of Visual Basic.

Whether the environment is MDI or SDI, the Visual Basic start-up environment frequently displays the windows and utilities in the Table 1.1 below.  These windows and utilities are described in detail later.

Table 1.1  Visual Basic Startup Windows
Project Explorer window This window is frequently positioned on the right of the Visual Basic container. It lists the modules that make up a Visual Basic project
Form Module window This Window displays a form if a form is selected for viewing in the Project Explorer. This form is selected for viewing in the Project Explorer. This form is the "canvas" upon which controls are placed.
Properties window This window displays the properties for whatever object has focus - whether a module or control.
Toolbox window This window displays controls for placing on forms.

The MDI Design Environment: Using Dockable Windows

The multiple-document interface for Visual Basic 5.0 is new.  It allows you to configure the Visual Basic design environment in many ways, but it can be confusing.  In order to use it effectively, you must have a large screen set to a fairly high resolution; otherwise, you will quickly suffer from screen clutter.  It also requires that you know how to work with dockable windows, an interface feature designed for those who prefer to use a mouse, rather than the keyboard, as a principal input device.

If you have not used dockable windows inside a container before, you might find them frustrating at first.  Dockable windows allow you to take any window inside a container and dock it on the perimeter of the container.  As you move a window inside a container by keeping your mouse button depressed on the window title bar while moving it, an outline of the window is displayed.  The width of this band gives you a visual cue as to what you can do with the window.  A thick band outline indicates it will become free-floating if released by the mouse button.  Figure 1.8  shows the toolbox docked to the right-hand side of a form.

Figure 1.8 The toolbox will be docked at the side of the Visual Basic form when the Dockable command (right-mouse button) is selected.

Given the capability to dock any window at any position in the Visual Basic MDI container, it is possible to customize the environment to your liking.  Many developers prefer to dock the toolbox at the bottom of the container in order to make room for form design.

To view a window or toolbar that is not displayed, choose View from the Visual Basic menu to see a list of windows and design-time utilities.

The capability to dock windows within the MDI environment can be controlled through the Docking tab of the Options dialog box (choose Tools, Options).  If the docking option for a window is not selected (see Figure 1.9), it will remain free floating.

Figure 1.9 The Docking tab of the Options dialog box presents many possibilities for docking the Visual Basic windows and design tools, such as the Color palace.

The SDI Design Environment: Using Free-Floating Windows

The single-document interface, the one preferred by the authors, essentially makes all windows free-floating outside of any container.  This increases the amount of screen “real estate” available, which is important in the rich (and often times cluttered) design environment of Visual Basic.  The SDI design environment is probably also more familiar to you from working other Windows applications, including earlier versions of Visual Basic.

To move to an SDI environment, select the Advanced tab in the Options dialog box (by choosing Tools, Options), as shown in the image below.

Figure 1.10  The SDI selection in the Options dialog box creates a design environment in which windows remain separate and are no longer docked.

Once the SDI environment is selected, a dialog box will appear, informing you that your selection will take effect the next time Visual Basic is launched.  To view the SDI environment, exit Visual Basic (by choosing File, Exit), and launch Visual Basic again.  You will now be in an SDI environment similar to the one you see in Figure 1.11.  To view individual windows and toolbars, you can make selections under the Visual Basic View menu.

Figure 1.11  The Visual Basic single-document interface (SDI) features free-floating windows, and is good to use when you work on a small screen.

Running Visual Basic Applications

Now that you are a bit more familiar with the Visual Basic design environment, let’s run several Visual Basic applications.

Share:

Software Components

After all of this discussion of classes and objects, you might be asking yourself, why all the fuss about objects?  What are the advantages of using objects?

The real benefit of objects is that, developed properly, they provide software that is reusable and robust.  The continuing dilemma of software development has been to create reliable code much faster and at lower cost.  Some claim that it is an impossible task.  More than a few software developers have a large sign posted above their doors: “Software Developed: Fast, Cheap, Good. Choose Two.”

Although object-oriented design has certainly not proved to be a magic bullet to shoot the beast of software development costs, it has helped create reliable, reusable software components.  Visual Basic components include the following:

  • Visible controls (the tools represented in the Visual Basic toolbox)
  • Software libraries that can be reliably used by many applications (ActiveX DLLs)
  • Executable programs that can be used by other programs (ActiveX EXEs)

These components make single or multiple objects available to the developer.

Different types software components are introduced and used here.  You will build applications using software components, and in the case of ActiveX DLLs, build a software component yourself.  Software components make possible rapid development of applications by acting as the building blocks of an application.  Each software component provides a particular service to the application.  One way to think about software components is to see them as servers to client applications.

How do you know which software components are available to you?  Visual Basic provides the Object Browser utility to let you examine your choices.

Launching Visual Basic and the Object Browser

In this exercise, you will start Visual Basic and then use Object Browser to examine Visual Basic objects.  You are provided step-by-step instructions.  Don’t be alarmed if you see unfamiliar windows.  The Visual Basic environment is explained in greater detail later in “Writing and Running Your First Visual Basic Program”, and “Adding Controls and Event Procedures to Form Modules.”  This exercise assumes Visual Basic has been installed on your computer.

  1. Start Visual Basic from the Windows Start Menu.
  2. When Visual Basic launches, a dialog box similar to that shown below appears.  If this dialog box does not appear, select Project, New from the Visual basic menu.

    The Visual Basic startup dialog box contains several types of new projects, including the Standard EXE project.

  3. Click the Open button for a new Standard EXE project (or click OK if you opened the dialog box from the Visual Basic menu). The Visual Basic design environment will appear. It should look somewhat similar to the design environment you see illustrated earlier. It will appear similar, but not identical. As you will discover in the next section, the Visual Basic design environment is almost infinitely configurable by you. There really is no standard Visual Basic design environment.
  4. Press the F2 key or select View, Object Browser from the Visual Basic Menu. Object Browser will appear as shown below.
  5. Select the VB library from the combo box in the upper-left corner of Object Browser, as shown below (You have used this kind of Windows object before, but you may not have known that was called a combo box.)

    The VB Object Browser lists the software classes available to you from the Visual Basic class library

  6. The classes through which you can scroll are listed on the left-hand side of Object Browser. Select the TextBox class of the VB Library and then examine the properties, methods, and events of the TextBox class in the right-hand list box.

Notice that the Object Browser icons indicate whether the class element (called a class member) is a property (the icon depicting a small hand holding a piece of paper), a method (the icon depicting a small green rectangle), or an event (the icon depicting a small thunderbolt).  The image below shows these three icons.

Object Browser displays information about classes, in this case the TextBox classes, and shows properties of the class, class events, and class methods.

As you examine the TextBox class and select different properties, methods, and events, observe the bottom of Object Browser where the class member is described.

Technorati Tags: ,,
Share:

Invisible Objects in Visual Basic

Not all objects in Visual Basic are visible and displayed to the user.  Neither are all object windows.  Visual Basic contains system objects that are available to use, although they are not displayed in the toolbox, including the following:

  • App – This object stores information about the application, including its name, path (where it is stored), and the files it requires.  This object can also activate an application.
  • clipboard – This object is a temporary storage location.  It allows text, graphics and computer code to be transferred from one part of an application to another part or from one application to another.
  • screen – This object references the entire video display screen.  It manipulates the size and placement of forms on the screen.
  • Debug – This object permits the display of information about a program while it is being developed.
  • Printer – This object determines how text and graphics are printed on a page and how output is sent to the printer.

These are system objects because the Windows operating system keeps information about each one.  For example, when you set up Windows, you must designate the computer printer to be used to send output to the printer.  When a specific printer is selected, Windows stores information about its makeup, such as the paper width and length.  In Visual Basic, you never have to use your printer’s name in a program.  Instead, you can instruct your printer to print directly by using the Printer object.

System objects will become important later.  For now, you should simply be aware that they exist and of what they do.

Technorati Tags:
Share:

Understanding Objects as Instances of Classes

In the last example the two text boxes and the form we have tried are referred to as windows as well as objects.  In a Windows program, just about everything that you see on the screen is a window, and many items that you don’t see are windows.

In a standard Windows word processing program, such as Word or WordPerfect, every button on the toolbars is a separate window.  Every open document is a separate window, as are the dialog boxes that permit you to select different font properties, and the rulers that allow you to set tabs and adjust page width.  These windows are objects, which have their own properties, methods, and events.  The Windows operating system sends messages to the windows to respond to user events.

Object Classes

How many different kinds of windows can there be? As many as a programmer can imagine and create!  The design of the windows operating system provides several standard window types called classes.  There can be many classes of objects in addition to the standard types.  Whether you know it or not, you probably are already familiar with several standard Windows classes and their behaviors, including the following:

  • Button
  • ComboBox
  • Edit
  • ListBox
  • Scrollbar

As you might suspect by now, some of the controls in the Visual Basic toolbox are related to these standard Windows classes.  For example, a Text Box control is closely related to the base Windows Edit class.

A class is like a cookie cutter: It defines how an object should look and behave when it is first created.  to work with Visual Basic objects, you first use this cookie cutter to cut out the uniform shape of your object.  After you have this basic shape (called an instance of the class), you can manipulate the object by altering its properties or by calling one of the object’s methods to make the object behave in a certain way.

Often Visual Basic creates an instance of a class for you.  When you add a Text Box control to a form, Visual Basic creates an instance of the visual Basic Text Box control class.  After it is created, you can manipulate it.  To alter text displayed in a text box objects named txtDisplay, for instance, you would execute the following instruction:

txtDisplay.Text = "Welcome to Visual Basic"

In other circumstances, you will be required to create an instance of the class (an object) yourself.  You will even define your own classes and then create multiple instances (objects) from the class you have defined.

Technorati Tags:
Share:

Visual Basic Statements and Instructions

The discussion of objects and encapsulation in "Forms and Controls", uses several lines of Visual Basic code, including examples of object properties being assigned values and methods being invoked.  The terms code and instructions can be used interchangeably, but the term statement means something specific in Visual Basic.

Visual Basic Statements

A statement differs from the assignment of a property or invocation of a method.  Consider the following definition: A statement is a reserved word that causes a computer program or the operating system to do something.  Statements are instruction (code) that are built in to the Visual Basic language.  Methods are code held by an object.

If you look at the Visual Basic Help, you discover that some keywords are statements.  for example, the keyword End is a statement that ends (stops) the execution of a Visual Basic program.  The keyword Kill (sorry, this is in the language) is a statement that deletes a file from a disk.

As another example, the statement to force explicit declaration of all variables is written as follows:

Option Explicit

In this example, no reference to an object is required because the statement is built into the language.

Visual Basic Program Instructions

Methods, statements and Visual Basic instructions are different.  An instruction is simply a line of code in a Visual Basic application.  Instructions contain the names of constants, variables, functions, properties, methods and built-in Visual Basic statements.  The rule to remember regarding instructions is that all instructions begin with a statement or the invocation of an object method.

  For example, an instruction beginning with a statement is as follows:

End

The following is an instruction beginning with a method:

List1.AddItem Entry

The method is AddItem and the object is List1.

Finally, some instructions beginning with methods or statements also contain what are known as statement or method arguments.  Consider the following:

Form1.Move Left + (width \ 10), Top + (Height \ 10)

In this instruction, Move is a method and Left, width, Top and Height are properties of the object, Form1 that are used as method arguments.  An example of a built-in Visual Basic statement that takes an argument is the AppActivate statement:

AppActivate “Calculator”

In this case, the statement shifts focus to a running instance of the Calculator utility bundled with Windows.

This all may seem a bit confusing right now, but you will get used to working with objects, methods and statements once you begin writing Visual Basic programs.

Technorati Tags: ,
Share:

A Closer Look at Encapsulation

Object properties, methods and events make up what is known as the objects interface.  this interface may be considered the private view of the object and it describes how that object can be manipulated.  Objects also have a private view: the data and code that the object does not expose to public view, but retains in order to execute its functions.  When you invoke the clear method of a List Box control, for example, you do not know how the list box clears its contents.  It just does it and you know that it works.  To illustrate encapsulation, let’s conduct a brief and simple exercise.

  1. Start-->All Programs -->Microsoft Visual Basic 5.0-->Visual Basic 5.0
  2. Select Standard EXE Project from the Project Type Window.
  3. The Project Window is displayed with a Blank Form (Form1).
  4. Select the Text Box Tool from the Toolbox and draw a Text Box on Form1.
  5. Draw Another Text Box below the first Text Box.
  6. Select Start from the Run Menu.
  7. Set the insertion point in the upper text box and type Microsoft Visual Basic.
  8. Select the text you have written using your mouse (or hold the Shift key down and use the directional keys).
  9. Copy the selected text onto the Windows Clipboard (Ctrl+C).
  10. Using the Tab key, shift to the lower text box and paste the text (Ctrl+V) from the Clipboard into the lower text box.
  11. Using the Backspace key, delete part of the text that you pasted.
  12. You can maximize the Form to fit in the Application Window or minimize it to remain as an icon on the task bar.
  13. Click on the Close Button of the Form at the right top corner to stop running the program.

Consider all the functionality contained within this application without a single line of Visual Basic code being written.  Three windows, a form, and two text boxes, were created.  One of these windows, the form, uses the default colors specified in the Windows Control Panel.  This form can be resized, minimized into an icon, or maximized to fill the entire screen.  It can be moved around the screen with the mouse.

The two text boxes allow the user to erase existing text and type text.  Text could be copied and pasted.  The text controls even indicate the user’s location by displaying a cursor.

How does the Text Box control manage the insertion point?  How does it "know" to erase text when the Backspace key is pressed?  You don't know.  That's the private view of the Text Box object.  You don't really have to know the inner workings of the Text Box object.  It works, and you can use it to build your own applications.  That's the power of encapsulation!

Technorati Tags: ,,
Share:

Object Properties

A property is a named attribute of an object.  Properties are used to change the appearance and behavior of objects, such as forms and controls.  These properties include attributes affecting the color, size, and name of the object.

Let’s take an everyday object, such as a shirt.  Suppose you write the following:

Shirt.Color = “Blue”

In Visual Basic, this would tell you that you have an object named Shirt. One of the properties of the shirt is color. You can change the color by assigning a new one, such as "Blue". You might want to set the shirt property as

Shirt.launder = “Clean”

as opposed to

Shirt.launder = “Dirty”

In the example, the condition of the shirt – clean or dirty – can be set directly.  Wouldn't it be great if your shirts were always clean?

For a Visual Basic object, such as a form, you can write instructions to alter it.  The following instruction changes the color of a form named Form1 to blue:

Form1.BackColor = vbBlue

Object Methods

The concept of an object method is more difficult than the concept of a property.  Methods are computer instructions (code) held by an object that operate on the object’s data.  Methods are written in a different way than properties.  The syntax (required way) for describing the application of a method to an object is written as follows:

object.Method

Perhaps an analogy will make methods more understandable.  Suppose you had a very compliant dog named Sparkyy.  By invoking the following methods of Sparky, you would get the behavior from Sparky that you desire:

Sparky.eat

Sparky.bark

Sparky.scat

Object methods in Visual Basic are similar.  One method for a List Box control (a control that displays a list of different text items) is the Clear method.  To clear the contents of the list box, you would write the following instruction:

List.Clear

When working with object properties in Visual Basic, you are either assigning them a new value (for example, Form1.BackColor = vbBlue), or you are reading their values (for example, mycolor = Form1.BackColor). Object methods, by contrast, are invoked with the object.Method syntax (for example, List1.Clear).  The distinctions between object methods and object Properties will become familiar to you as you work with Visual Basic objects.

Object Events

While the value of a property can be set and a method can be invoked, an object event is an action taken by the object when notified by a message.  An object event might be a mouse click.  The handling of object events is an operating system responsibility.  The Windows operating system sends messages to windows (objects) for different events.

Remember the words message and action.  If the user clicks a mouse button on a Visual Basic form, the operating system sends a message to the form.  The Visual Basic designer can choose to execute code (the action) in response to the message or ignore it.  For example, an image on a form might be programmed to take some action when it is clicked.  It might take some other action when it is dragged across the form.  The Visual Basic programmer writes coded instructions for the events that should be assigned to the form or control.  Visual Basic code, for instance, executes instructions by invoking a form’s Print method when the user clicks the form.

Private Sub Form_Click()
  Form1.Print "You clicked the form1"
End Sub
Share:

Forms and Controls

What, exactly, does the phrase "encapsulates the Windows PI" mean?  Encapsulation is a key concept for any object-oriented programming language.  It refers to the capability of an object to hide its internal workings from other objects.  In turn, the object allows itself to be manipulated by the programmer and other objects through the use of three key object features: properties, methods, and events.

Let’s consider two kinds of objects that you have seen in the Visual Basic startup screen: forms and controls.  The image below shows a Window that contains a form named Form1.  This form acts as a container for controls.  You could think of Form1 as a blank piece of paper that you must fill in.  You use this blank form to design the user interface for a Visual Basic application.  When you begin the design of a Visual Basic program, you start with a blank form and, with a set of tools, begin to design the user interface.

The tools you use to construct the interface are called controls, which are attached to forms.  Examples of controls are shown on the toolbox and include a text box (a box the user types text into), a command button (an on-screen button that the user can click), and a label (an area on the form to place a text heading).  If the toolbox is not visible, select View, Toolbox on the menu bar, or click the toolbox button on the toolbar to display it.

Because forms and controls are objects, they can be manipulated by properties, methods, and events.  Let’s consider each of these object features in turn.

Share:

Popular Posts

Search This Blog

Powered by Blogger.

Featured Post

Coded Statements and Methods

In the preceding procedure , you wrote several coded instructions, which introduced two different programming statements and a method: the D...

Recent Posts