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

Ad

Showing posts with label Introduction. Show all posts
Showing posts with label Introduction. Show all posts

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:

Understanding the Relationship of VB to Windows

All application programs (the kind of programs developed with such languages as Visual Basic) must be developed to work with a specific operating system.  Application Programs interact with operating systems by using operating system functions that applications developers can exploit.  These functions are usually referred to as application program interface (API) functions.  API functions allow programmers to add such functionality to their programs as opening and saving files, checking system hardware, using the computer’s internal clock, and, in the Microsoft Windows family of operating systems, creating, modifying, and communicating with Windows.

The Windows API is enormously complex.  It has over 800 functions, some of which can perform a wide variety of tasks.  The value of Visual Basic is that it greatly simplifies Windows programming.  Visual Basic encapsulates the Windows API into objects that Visual Basic programmers can manipulate.  For example, when you use the C programming language, creating a program that greets the user with the message " Welcome to Visual Basic" can take several lines of instructions.  In Visual Basic, however, the same program requires only a single line.

Share:

Evolution of Visual Basic

In the last several years, Visual Basic has evolved rapidly.  Until recently, Visual Basic was a proprietary language used only by Microsoft products.  Microsoft now licenses Visual Basic for Applications to those software developers who want to add programmability to their applications.  This will increase Visual Basic prevalence.

Visual Basic is now the universal macro language for the Microsoft Office suite of applications.  The newest version of Word, for instance, has migrated to Visual Basic for Applications.  Other large programmable application, such as Microsoft Project, also use Visual Basic for Applications.

Another important development of the Visual Basic language is the advent of the Visual Basic Scripting Edition (also known as VBScript) for developing Internet-enabled applications.  The capability of Visual Basic to create downloadable ActiveX components and the capability of VBScript to manipulate Internet browsers and Internet documents (HTML documents) suggests Visual Basic will play a major role in the explosion of Internet and intranet application.

This text assumes you have the Standard, Professional, or Enterprise Editions of Visual Basic.  All chapters other than the database chapters can be completed using the Standard Edition of Visual Basic, but you will need the Professional Edition to work with Data Access Objects “Using Data Access Objects.”  Microsoft Office will also need to be installed on your computer.

Share:

Interpreted or Compiled Languages

Computer languages can be interpreted or compiled.  An interpreter executes a program, while a compiled language uses a compiler to translate the high-level language into machine language.  Visual Basic is now both an interpreted language and a compiled language.  The developer has a choice when creating a Visual Basic executable whether to make a compiled program or an interpreted program.  You will create both types of programs here.

The main advantage of an interpreted language is immediate response.  Program development often goes faster because the code instructions can be easily modified and immediately tested without being compiled (or translated) first.  This saves you considerable time in writing and testing a program.  The main disadvantage of an interpreted program is speed of execution – especially in processor-intensive instructions.  An interpreted program must translate instructions each time a program is run.  This is not required of a compiled program.

The advent of compilation in Visual Basic 5 has dramatically sped up numeric calculations and most other computations.  The speed by which forms now load into memory in Visual Basic 5 is one of the language’s more dramatic speed improvements.  But compilation alone does not guarantee speed.  Design of a program is one of the more important determinants of performance.  Visual Basic programs, whether they are interpreted or compiled, rely upon other runtime libraries of functions in order to execute.  These libraries are probably the largest factor in Visual Basic performance.

Share:

Low-Visual and High-Visual Languages

Computer languages can be described as having a low-visual or a high-visual orientation.  Prior to 1990, most languages were low-visual languages, so programmers had considerable difficulty designing the computer forms and reports, data entry screens, and navigation tools by which to move from one area of a computer program to another.  High-visual languages greatly simplify the tasks of designing forms, screens, and navigation tools.  For this and other reasons, Visual Basic is known as a rapid prototyping language.  Its design tools let you quickly design a version or prototype of a computer application.

Low-Visual Languages

Let’s consider how a low-visual language differs from a high-visual language.  Low-visual languages are not supported by a GUI.  Instead, the programmer usually works with a blank terminal screen, adding line after line of instruction to that screen.  After the instructions are entered, the programmer issues a Run or Execute command to execute the instructions.  Only at this time do visual images appear on the screen.  Those of you who use common DOS-level commands, such as Copy, Del or CD use a low-visual language. 

High-Visual Languages

High-visual languages are supported by a GUI design environment.  The appearance of the design environment is conceived to improve speed in program design and can even be customized to suit your needs.  At the top of the screen is a menu bar, which contains the File, Edit, View, Project, Format, Debug Run, Tools, Add-Ins, Window and Help menus.  Below the menu bar is a toolbar.

The buttons appearing on the toolbar allow quick access to the most commonly used commands.  As you work through the exercises you will become familiar with the use of each tool in the toolbox.  Finally, the Visual Basic startup screen often contains a Form Window, a Project (Explorer) Window and a Properties Window.  “Writing and Running Your First Visual Basic Program,” asks you to use each in constructing a Visual Basic Program.

Pause and Breathe for a Moment!

Looking at the toolbar and toolbox the first time might fill your heart with fear.  You might exclaim, I can’t remember what all those icons mean!  With Visual Basic, help is readily on hand.  To quickly identify a control, just let your mouse pointer linger over an item in the toolbox.  A ToolTip appears by your pointer and identifies the control.  The same applies for buttons on the toolbar.  You can also click the button you want to inspect and press the Help key: the F1 function key on the keyboard.  The Visual Basic Help screen appears with a description of the button.

Share:

Procedure-Oriented and Event-Oriented Languages

Besides low-level and high-level languages, computer languages can be classified as procedure-oriented or event-oriented.  Procedure-oriented languages tend to run without human interference or the taking of some action by the user: A computer program is executed by a simple run instruction, and usually runs from top to bottom, with all the code executed until the program ends.  Event-oriented languages are different in that they depend on the user: They wait for the user to take some action before they execute.  The program waits for an event (or happening) to occur before beginning a program execution.

Procedure-Oriented Languages

Prior to 1990, most commercial high-level languages were procedure-oriented languages.  The emphasis in writing a computer program was to identify a set of processing tasks and to describe the steps important to each task.  Collectively, the set of tasks represented a procedure: a listing of a set of tasks required to perform an activity.  As an example, consider the procedure required in processing an employee paycheck, in which the steps of the procedure are expressed as tasks:

  1. Get employee name.
  2. Get hours worked.
  3. Get hourly wage.
  4. Multiply hours worked by the hourly wage to compute gross pay.
  5. Compute taxes based on gross pay.
  6. Subtract taxes and other deduction (such as union dues) from gross pay to compute net pay.
  7. Print the employee’s check.

This procedure could be used in writing a QBasic program. The following code listing shows a partial QBasic program written to print an employee’s check.  Even though you may not know the QBasic language, you should be able to understand, step by step, how the computer processes an employee paycheck.

'Compute and print a payroll check
'Initialize variables
emp.name$ = "Roger Rabbit"
pay.date$ = "06/12/99"
hours.worked = 40              
'Total hours worked
rate = 7.50                    
'pay per hour
tax.rate = 0.25                
'Tax percentage
'Compute gross and net pay
gross.pay = hours.worked * rate
taxes = gross.pay * tax.rate
net.pay = gross.pay - taxes
'Display the results
PRINT TAB(40); "Date: "; pay.date$
PRINT
PRINT "Pay to the order of: "; emp.name$
PRINT
PRINT "Pay the full amount of: "; gross.pay
PRINT TAB(28); "---"
PRINT
PRINT TAB(40); "------------------"
PRINT TAB(40); "W. Pinchpenney, treasurer"

Event-Oriented Languages

Event-oriented languages became possible with the advent of the Macintosh operating system for Apple Macintosh computers and Microsoft Windows for MS-DOS computer systems.  Both environments were designed to bring hardware and software together into a standard user interface by employing a graphical user interface, or GUI (pronounced goo-ey).  A GUI simplifies learning:  Once you learn how to work with one application using the interface, it is easy to learn another application because the interface remains the same.

An event-oriented language implies that an application (the computer program) waits for an event to occur before taking any action.  What is an event?  It might be the press of a key on the keyboard or the click of a mouse button.  With these events (these are many types), the computer waits for a key press or a mouse click (pushing a button on a hand-held mouse).

Share:

Learning How VB Differs from other Languages

Of the 1,000 or so computer languages that have been developed, each language can be categorized based upon the following criteria:

  • Low-level or High-level
  • Procedure-oriented or Event-oriented
  • High-visual or Low-visual
  • Interpreted or compiled

Imagine 1,000 or so languages!  Where does Visual Basic fit?  This section helps to explain not only where Visual Basic fits, but why it is different from many other programming languages.

Low-level and High-level Languages

A computer language can be described as a low-level or high-level language based on how close the language is to machine language (which depicts a low-level language) or to English (which depicts a high-level language).  Let’s look at what we mean by this difference in language.

Low-Level Language

Low-level languages are machine oriented.  These languages work close to machine language, which is limited to 0s and 1s.  Why only 0s and 1s?  This is the language the computer understands or it works by turning electronic circuits Off (0)  and circuits On (1).  By making a language closer to 0s and 1s, the speed at which the computer processes data improves.

An example of a low-level language is assembly language code.  With this language, such instructions as the following tell the computer to save, move, add and store the results of processing:


PUSH BX
PUSH AX
MOV AX, @A
MOVE BX, @B
ADD BX, AX
MOV @B, BX
POP BX
POP AX

Assembly language code uses mnemonics (memory aids), for which such words as ADD and POP make it easier to remember what an assembly instruction does.  While not quite 0s and 1s, you deal with the exact steps the computer must take in processing data when programming in assembly language.

Low-level languages are said to have one-to-one relationship with the computer.  A programmer must write an explicit instruction for every operation of the machine.  A low-level language is precise.  Programmers use low-level language code for such tasks as writing operating systems (the software that enables your computer to operate).

High-Level Language

High-level language are more people-oriented.  These languages have a one-to-many relationship, in which one instruction leads to a series of machine-level instructions.  These languages feature more English and English-like words.  In Visual Basic, examples of these English-like words are If, Else, Dim (for dimension), and OpenDatabase.

Because of this one-to-many relationship, high-level languages are easier to learn, use and understand.  However, they do require more machine time to translate a single instruction into a set of machine-level instructions.

Programmers (those who write computer programs) use high-level languages in writing application programs.  For example, a high-level language, such as Visual Basic, would be used to write the instructions for processing a company payroll.  Application programs define the ways by which users are able to use the computer.

Share:

Running a Visual Basic Program

Welcome to the world of Visual Basic.  Released by Microsoft in 1991, Visual Basic was designed to be a visually oriented programming language in contrast to the popular languages of that time (Pascal, C, COBOL, and FORTRAN).  Although Visual Basic is similar to QBasic – the procedural languages supplied with every version of MS-DOS beginning with version 5.0 – it contains important extensions that make it more of an object-oriented  language.

The newest version of Visual Basic is more object-oriented than ever.  It is capable of handling software development projects of enormous scope and depth.  Visual Basic is now one of the most flexible and powerful visual object-oriented computer language available, and it remains the most popular language for the world’s most popular operating system.

One way of describing Visual Basic's nature is to say that when the computer programmer develops programs in Visual Basic, data is more often than not approached as an object rather than just numeric or text information.  Data Objects, like real-world objects, such as desks and chairs, have properties.  Desks and chairs could be said to have a “Leg Count” property, which describes the number of legs for that object, whether it is a three-legged stool or a four legged desk.  Similarly, a data object that held information about a store’s customers might have a CustomerCount Property.  Unlike the "LegCoung" physical property of a real-world chair, you can easily change the  CustomerCount property of a data object.

Share:

Introduction

Visual Basic is the most popular programming language for the world’s most popular operating system.  By encapsulating the complexities of the windows application program interface (API) into easily manipulated objects, Visual Basic is the first language people consider when they want rapid application development for the Windows environment.  The capability of custom controls to easily extend the language has made Visual Basic a popular choice for an amazingly wide variety of programming tasks.

However, the easy accessibility of the language and its enormous breadth pose challenges to both the students and the instructor.  Students approach the language from a wide variety of backgrounds and abilities: Some are new to programming; some have extensive programming experience in other languages (often character-based procedural languages); some want to learn the language to accomplish a very specific task.

Frequently, instructions are challenged by the variety of students who come together in a course.  A senior engineer from an aerospace company sits right next to a programming neophyte.  Some students are comfortable working with a visual programming environment, while others find the design paradigm quite difficult.  Consequently, teaching materials must be flexible enough to accommodate a broad range of backgrounds.

Next: Running a Visual Basic Program

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