Introduction to Visual Basic by gregoria

VIEWS: 349 PAGES: 20

									1             Introduction to Visual Basic




Although this book is based around developing projects, it is important to have
at least a basic understanding of the Visual Basic environment. As a result, this
chapter introduces you to Visual Basic and guides you through the creation of your
first Visual Basic program. Topics that you’ll be exposed to include the basics of the
Visual Basic language, variables, the built-in components, the ingredients that make
up a basic application and the Integrated Development Environment (IDE).




                                                                                    1
2   Learning Visual Basic Through Applications



         The vast majority of screen shots and information pertain to the Visual Basic 6
    IDE. However, this chapter addresses the differences in the Visual Basic 6 and
    Visual Basic.NET IDEs and includes information on how to open and convert version
    6 projects to .NET.
         For those of you already familiar with Visual Basic, you can feel free to move
    ahead to Chapter 2 where we will begin working on a multimedia and audio CD
    player. However, if you are a beginner or an intermediate programmer, this chapter
    will build a solid foundation onto which you can base your future Visual Basic
    learning.

    The Integrated Development Environment
    The Visual Basic Integrated Development Environment (IDE) may be the single
    biggest reason for the vast popularity of Visual Basic. It provides everything you
    need to develop applications in an easy-to-use-and-learn Graphical User Interface
    (GUI – pronounced Gooey).
         Like many Windows applications, Visual Basic has several ways in which it can
    be opened. First, and probably the easiest way to access Visual Basic is through the
    Windows Start menu – the exact path required to access this shortcut is dependent
    upon your installation and may differ on individual machines. Another option is to
    create a shortcut on your desktop, which will execute Visual Basic by double-click-
    ing on it. Lastly, because Visual Basic sets up default associations when it is
    installed, you can also run it by double-clicking on files that end with a vpb (Visual
    Basic Project) extension.
         When you open Visual Basic, you’re presented with an opening screen that will
    appear very much like Figure 1.1. For most of the projects in this book, you will be
    creating Standard EXE files, so you should click the Open button or just press the
    Enter key. This standard type of project will create a standard Windows executable
    program that can be run outside of the IDE.
         As you can see in Figure 1.2, the Visual Basic IDE is fundamentally a collection
    of Menus, Toolbars, and Windows that come together to form the GUI. There are
    five main Windows that appear in the default Visual Basic IDE, along with the
    Standard Toolbar, Menu Bar, and Title Bar.
         If you have ever used VB5, the version 6 IDE will look very similar to you. In
    fact, the two versions are so close that you can probably begin working in version 6
    without looking over any additional documentation. If you have used Visual Basic
    version 4 or earlier, the IDE may take some getting used to, as Visual Basic 5 and 6
    have been changed to a Multiple Document Interface (MDI) application. If you are
    new to Visual Basic, the IDE can seem a little daunting at first glance. However, this
    will quickly fade away as you begin to become comfortable with each part.
                                                              Introduction to Visual Basic   3




                FIGURE 1.1 The New Project Window is displayed when Visual
                Basic is started.




FIGURE 1.2 Visual Basic offers an IDE that is both powerful and easy to use.
4       Learning Visual Basic Through Applications



        The Title Bar and Menu Bar
        As you can see in Figure 1.3, the Visual Basic IDE contains a Menu Bar and Title Bar
        that appears very similar to most Windows applications. The Title Bar serves as a
        quick reminder of what you are doing inside the IDE. For instance, unless you have
        changed something, the Title Bar should currently read “Project 1 – Microsoft
        Visual Basic [design].”




FIGURE 1.3 Menu Bars and Title Bars provide information similar to most Windows programs.


            The Menu Bar provides functions that you would expect from any standard
        Windows application. For instance, the File Menu allows you to Load and Save
        projects; the Edit Menu provides Cut, Copy, and Paste Commands that are familiar
        to most Windows users; and the Window Menu allows you to open and close
        Windows inside the IDE. Each Menu Option works like it would in any other
        Windows application, so they don’t need any real introduction. You shouldn’t be
        overly concerned with all of the options at this time, because we’ll be spending
        some time on them later in this chapter and throughout the book.


THE TOOLBARS


Standard Toolbar
        The Standard Toolbar, which is displayed in Figure 1.4, is also comparable to the
        one found in the vast majority of Windows applications. It provides shortcuts to
        many of the commonly used functions provided by Visual Basic and along with the
        Standard Toolbar, Microsoft has provided several additional built-in Toolbars that
        can make your job a little easier. To add or remove any of the Toolbars, you can
        right-click on the Menu Bar, or you can select Toolbars from the View Menu.




FIGURE 1.4 Toolbars provide shortcuts to many of the common functions.
                                                            Introduction to Visual Basic     5


Individual Toolbars
       The Individual Toolbars include the Debug, Edit and Form Editor Toolbars. The
       Debug Toolbar, which is visible in Figure 1.5, is utilized for resolving errors in your
       program and provides shortcuts to commands that are found in the Debug Menu.




       FIGURE 1.5 Shortcuts in the Debug Toolbar are helpful for finding errors in your program.



       The Edit Toolbar
       In Figure 1.6, you will find the Edit Toolbar, which can be useful when you’re
       editing code and setting breakpoints and bookmarks. This Toolbar contains
       Commands that can be located in the Edit Menu.




       FIGURE 1.6 The Edit Toolbar offers a variety of time-saving features.



The Form Editor Toolbar
       The Form Editor Toolbar (see Figure 1.7) includes most of the Commands in the
       Format Menu and is useful only when you’re arranging Controls on a Form’s surface.




                          FIGURE 1.7 The Form Editor Toolbar displays Buttons
                          specific to Form editing features.



            Whether you decide to display these Toolbars is purely a matter of personal
       taste, as the functions they provide are generally available in Menu Options. Several
       factors, such as your screen size and resolution, may make their use impractical.
6   Learning Visual Basic Through Applications



        You can create a custom Toolbar or customize the appearance of the built-in
    Toolbars by following a couple of steps. First, right-click on any Toolbar, and then
    select the Customize option. From the Customize Window that appears, click the
    New button and type a name for the new Toolbar. The name will appear in the
    Toolbar list, and after making sure that its check box is selected, click the
    Commands Tab, which displays a list of available Menu Commands. From the list
    of categories and Commands, select the options you would like to have on your
    Toolbar. The changes are automatically saved, so continue placing options on the
    Toolbar until you are finished and then simply close the Window. You can now use
    your Toolbar like any other.


THE WINDOWS

    In addition to the Menus and Toolbars, there are several Windows that you need to
    become familiar with in order to get a basic grasp of the Visual Basic IDE. The Form
    Window displays the basic building block of Visual Basic applications. The Code
    Window is where you enter code for your application. The Toolbox Window
    displays some of the built-in Visual Basic Controls. You can set properties of the
    components and Forms with the Properties Window. Lastly, the Project Explorer
    displays the Objects that make up the project you are working on and you can
    position and view the Forms with the Form Layout Window.


    The Toolbox
            The Toolbox, which can be seen in
            Figure 1.8, is probably the Window
            that you will become familiar with the
            quickest, as it provides access to all of
            the standard Controls that reside
            within the Visual Basic runtime itself.
            These Controls, known as intrinsic
            Controls, cannot be removed from
            the Toolbox, and include the following
            options.




                                                 FIGURE 1.8 Standard Controls, as well as
                                                 ActiveX Controls, are displayed in the Toolbox.
                                             Introduction to Visual Basic    7


Pointer: The pointer is the only item on the Toolbox that isn’t a Control.
You can use it to select Controls that have already been placed on a Form.

PictureBox: You use the Picture Box Control to display images in several
different graphics formats such as BMP, GIF, and JPEG among others.

Label: The Label Control is used to display text information that does not have
a need to be edited by an end user. It’s often displayed next to additional
Controls such as Text Boxes to label their use.

TextBox: You use Text Box Controls for user input. It may be the most widely
used Control.

Frame: A Frame Control is typically used for containing other Controls and for
dividing the GUI. Controls placed within a Frame cannot be displayed outside
of it, and if the Frame is moved on the Form, the Controls are moved with it.

CommandButton: Much like the Text Box Control, Command Button
Controls are used for input on almost every Form. They are used as standard
buttons for input like OK or Cancel.

CheckBox: If you need the ability to select True/False or Yes/No, the Check Box
Control is the correct Control.

OptionButton: The Option Button Control is similar to the Check Box Control
in that it offers the ability to select an option. However, an Option Button
Control is most often used when a group of options exists and only one item
can be selected. All additional items are deselected when a choice is made.

ListBox: The List Box Control contains a list of items, allowing an end user to
select one or more items.

ComboBox: Combo Box Controls are similar to List Box Controls, but they
only provide support for a single selection.

ScrollBars: The HScrollBar and VScrollBar Controls let you create scroll bars
but are used infrequently because many Controls provide the ability to display
their own Scroll Bars.
8   Learning Visual Basic Through Applications



        Timer: The Timer Control is an oddity when it is compared to other Controls,
        in that it isn’t displayed at runtime. It’s used to provide timed functions for
        certain events.

        DriveListBox, DirListBox, FileListBox: These Controls can be used individually,
        but many times are used together to provide dialog boxes (also known as windows
        in this book) that display the contents of Drives, Directories, and Files.

        Shape, Line: The Shape and Line Controls are simply used to display lines,
        rectangles, circles, and ovals on Forms.

        Image: You can think of the Image Control as a lighter version of the Picture
        Box Control, and although it doesn’t provide all of the functionality that the
        Picture Box Control does, it consumes fewer resources. As a result, you should
        use the Image Control whenever possible.

        Data: The Data Control is a component that allows you to connect one or more
        Controls on a Form to fields in a database.

        OLE: The OLE (Object Linking and Embedding) Control can host Windows
        belonging to other executable programs. For instance, you can use it to display
        a spreadsheet generated by Microsoft Excel or a Word document.

        Some of the intrinsic Controls are used more frequently and you are likely to
    become acquainted with them much faster. The TextBox, Command Button, and
    Label Controls are used in almost all Visual Basic developed applications. While
    some Controls are very important, others may provide functionality that can be
    replaced by far superior Controls. For instance, you probably shouldn’t use the
    Data Control, as it cannot be used with ActiveX Data Objects (ADO) data sources.

        Additional Controls, known as ActiveX Controls (sometimes referred to as
    OCX Controls or OLE custom Controls), provide additional functionality and can
    be added to the Toolbox for use in a project. These components are provided by
    many third party companies or may have been provided by Visual Basic itself.
    Many times, these Controls provide extended functionality that makes them much
    more powerful than the intrinsic Controls. That said, the built-in varieties offer a
    few advantages that cannot be overlooked. For instance, if you use a third party
    Control, you will need to distribute it with your application, whereas the intrinsic
    Controls are included with the Microsoft Visual Basic runtime file.
                                                        Introduction to Visual Basic   9


Form Window
     You need to have a place to assemble your Controls, and this is the function of
     Forms. As you can see in Figure 1.9, the Forms you work with are displayed inside
     the Form Designer Window. When they are displayed in this way, you can place
     and manipulate Controls.

Code Window
     Every Form has a Code Window, which is where you write the code for your
     program. The Code Window can be opened in a variety of ways such as double-
     clicking on a Form or choosing Code from the View Menu. Figure 1.10 displays a
     sample Code Window.




     FIGURE 1.9 During development, the Form Designer Window displays the Form you are
     working on.




     FIGURE 1.10 Visual Basic code is written in the Code Window.
10     Learning Visual Basic Through Applications


Project Explorer
       The Project Explorer can be seen in Figure 1.11 and is provided to help you
       manage projects. The Project Explorer is a hierarchical tree-branch structure that
       displays projects at the top of the tree. The components that make up a project,
       such as Forms, descend from the tree. This makes navigation quick and easy, as you
       can simply double-click on the part of the project you would like to work on. For
       instance, if you have a project with several Forms, you can simply double-click the
       particular Form you want to view.

           You can also display the Project Explorer at any time by pressing the F4 key. You
           can access the Code Window through a shortcut in the Project Explorer. Click on a
           form to highlight it. Once it is highlighted, you can display the code associated with
           it by clicking on the Code Window icon that is displayed at the upper left side of the
           Project Explorer.

           The Project Explorer also provides additional functions such as the ability to
       add new Forms or Code Modules (more on these in later chapters). You can add
       a Form to a project by right-clicking on an open area of the Project Explorer
       Window, and selecting Add from the pop-up Context Menu which can be seen in
       Figure 1.12.




       FIGURE 1.11 You’ll quickly realize
       the usefulness of the Project Explorer.



                                                        FIGURE 1.12 Pop-up Context Menus
                                                        make available countless valuable
                                                        features in the IDE.
                                                         Introduction to Visual Basic    11


Properties Window
      The Properties Window is used for the configuration of the Controls you place on
      a Form, as well as the Form itself. All of the standard Visual Basic Controls have
      properties, and the majority of ActiveX Controls do as well. As you can see in
      Figure 1.13, the Window displays the available properties for an individual Control,
      or the Forms that they are placed on. These properties can be changed as you
      design an application, or you can alter them in code.

          You can display the Properties Window at any time by pressing the F4 key.




Form Layout Window
      The Form Layout Window is visible in Figure 1.14. Its only purpose is to allow you
      to set the position of Forms when they are actually being executed during
      runtime. The process is very simple. You select the position of the Form by moving
      it on the small “screen” that represents your desktop. You should keep in mind,
      however, that the placement of your Form in the Form Designer Window does not
      affect its position during runtime execution.




                                                         FIGURE 1.14 You can change the
                                                         position of executed Forms with the
                                                         Form Layout Window.




      FIGURE 1.13 The Properties Window allows you to
      adjust properties for many Visual Basic Objects.
12      Learning Visual Basic Through Applications



Changes in Visual Basic.NET
        Visual Basic.NET is the next generation of Visual Basic and has been completely re-
        engineered by Microsoft. As you can see in Figure 1.15, Visual Basic.NET introduces
        some changes to the IDE and new Windows Forms and Web Forms. The product
        has truly been developed from the ground up and is not just an upgrade to Visual Basic 6.




FIGURE 1.15 The new IDE in Visual Basic.NET resembles earlier versions.


Upgrading Version 6 Projects to Visual Basic.NET
        Because of the new changes associated with Visual Basic.NET, your code will need
        to be upgraded before it can be used. Fortunately, the vast majority of time, this is
        very easy as it happens automatically when you open a Visual Basic 6 project in
        Visual Basic.NET. An Upgrade Wizard, which can be seen in Figure 1.16, steps you
        through the upgrade process and creates a new Visual Basic.NET project. The
        existing Visual Basic 6 project is left unchanged. If you have Visual Basic version 5
                                                           Introduction to Visual Basic   13


       projects, it’s best to upgrade them to version 6 before moving on to version 7
       (VB.NET).
           When your project is upgraded, the language is modified for any syntax
       changes and your Visual Basic 6.0 Forms are converted to Windows Forms.




                         FIGURE 1.16 The Upgrade Wizard makes it easy
                         to convert version 6 projects to Visual Basic.NET.


       Depending on your application, you may need to make minor changes to your code
       after it is upgraded. Many times this can be necessary because certain features either
       are not available in Visual Basic.NET, or the features have changed significantly
       enough to warrant manual changes to the code.
            Once your project is upgraded, Visual Basic.Net provides an “upgrade report”
       to help you make changes and review the status of your project. The items are
       displayed as tasks in the new Task List Window, so you can easily see what changes
       are required, and so you can navigate to the code statement simply by double-
       clicking the task. Many times, the document recommendations simply represent
       good programming practices, but they also identify the Visual Basic 6 Objects and
       methods that are no longer supported.

Working with Both Visual Basic 6.0 and Visual Basic.NET
       The Visual Basic.NET and Visual Basic 6.0 IDE’s can be used on the same computer
       and can even execute simultaneously. Additionally, applications written and
       compiled in Visual Basic.NET and Visual Basic 6.0 can be installed and executed on
       the same computer. Although the projects in this book have been written for Visual
       Basic 5 or 6, they should work equally well with Visual Basic.NET.
14     Learning Visual Basic Through Applications



A QUICK PROJECT

       Now that you have an understanding of the Visual Basic IDE, you can put the
       information to work with your first Visual Basic project. The first step to any
       application is to draw the user interface.

The User Interface
       The user interface is probably the first step you’ll take when you are developing
       an application. Start the Visual Basic IDE using one of the methods that were
       mentioned previously in the chapter and select Standard EXE from the first
       Window that appears and click the Open button.
           The next step is to place Controls on the default Form that appears. There are
       two separate approaches you can use to do this. First, you can simply double-click
       on one of the intrinsic Visual Basic Controls that appear in the Toolbox, which will
       place a single instance of the Control on the Form.
           Another way you can place Controls on the Form begins by clicking the Tool
       in the Toolbox. You then move the mouse pointer to the Form Window, and the
       pointer changes to a crosshair. Place the crosshair at the upper left corner of where
       you want the Control to be, press the left mouse button and hold it down while you
       drag the pointer toward the lower right corner. As you can see in Figure 1.17, when
       you release the mouse button, the Control is drawn.




                             FIGURE 1.17 You can place Controls on a
                             Form in several different ways.


           You don’t have to place Controls precisely where you want them, as you can
       move them as Visual Basic provides the necessary tool to reposition them at any
       time during the development process. To move a Control you have created with
                                                   Introduction to Visual Basic   15


either process, click the Object (anywhere on the Object except the edges) in the
Form Window and drag it, releasing the mouse button when you have it in the
correct location. You can resize a Control very easily as well, by clicking the Object
so that it is highlighted and the sizing handles appear. These handles, which can be
seen in Figure 1.18, can then be clicked and dragged to resize the Object.




                   FIGURE 1.18 Handles are useful resizing Objects.



    For a first project, you can begin by placing a Text Box and a Command
Button on the Form and positioning them so that they look something like Figure
1.19.




                     FIGURE 1.19 Beginnings of a GUI.
16   Learning Visual Basic Through Applications



         The next step is to double-click the Command Button on the Form, which will
     bring up the Code Window and leave you something that looks similar to Figure
     1.20. It’s worth noting that your window will currently only have the Private Sub
     Command_Click and End Sub lines. Visual Basic automatically creates those lines
     for all of its intrinsic controls for the most popular used event. In this example, a
     Command Button’s Click Event is its most popular so Visual Basic automatically
     places the lines in the Code Window.




                  FIGURE 1.20 When you double-click an Object on a Visual
                  Basic Form, it opens an event procedure in the Code Window.


         Depending on the way your version of Visual Basic has been set up, Visual Basic
         may or may not automatically place a line that reads “Option Explicit” when you
         first open the code window. Option explicit is used by Visual Basic to make sure
         that you declare all of your variables and is used by default throughout the book.
         If you don’t use the option explicit statement, all undeclared variables are treated
         as a variant type. You can either type this line at the top of the code window or you
         can have Visual Basic add it for you by selecting tools | options and clicking the
         “Require Variable Declaration” option.

          Your cursor should be flashing beneath the Private Sub Command1_Click()
     line. Type the following lines into your application (do not type the Private Sub or
                                                       Introduction to Visual Basic   17


    End Sub lines of code for any code shown in this book unless you are instructed to
    do so):

        Private Sub Command1_Click()
        Dim strInfo As String
          strInfo = "My first Visual Basic program."
          MsgBox strInfo
        End Sub


         From the drop down Menu located at the top left of the Code Window, select
    Form. A Form _Load event procedure is created for you automatically. Enter the
    following code and continue reading for an explanation:

        Private Sub Form_Load()
          Text1.Text = "Click the button to display a message"
        End Sub.


        The CD-ROM that is included in this book contains all of the sample code for each
        of the projects we’ll create throughout the book. This saves you time and program-
        ming mistakes, which will allow you to focus only on the task at hand—learning
        Visual Basic. It also contains several applications. Please see the CD-ROM for a
        complet list of applications and compiled applications.



THE CODE EXPLANATION

    That’s all we need for this application. Although this project is very simple, you are
    going to be introduced to a few items that you wouldn’t necessarily need for this
    easy of an application, but they are being presented in order to get you started in
    Visual Basic development. The first of these extras are variables, which are used by
    Visual Basic to hold information needed by your application. There are only a few
    simple rules you should keep in mind when you use variables. They should be less
    than 40 characters; they can include letters, numbers, and underscores (_); they
    cannot use one of the Visual Basic reserved words (i.e. you cannot name a variable
    Text); and they have to begin with a letter.

        Let’s look carefully at what the code you typed does. The “Private Sub
    Command1_Click()” tells Visual Basic to run this line of code when someone clicks
    on the Command Button you created called Command1. When they do click the
    Command Button, the lines of code you typed in are executed. The “End Sub”
18   Learning Visual Basic Through Applications



     simply informs Visual Basic that it’s time to stop running the code. The Private Sub
     and End Sub lines were created automatically for you when you double-clicked on
     the Command1 Button in a previous step.
          The Form_Load event was created automatically for you when you selected
     Form from the drop down Menu in the Code Window. Inside the event, you added
     a line that sets the Text Box equal to “Click the button to display a message”. Like
     the Command1_Click event, the code is run only when something occurs, which in
     this case, is the Form being loaded when the program runs.
          To use a variable in Visual Basic, you should declare it with the Dim statement.
     The first line of code that you entered for the Command1_Click event dimensions
     the variable strInfo as a string. The next line assigns the text string “My first Visual
     Basic program” to the variable and the final line uses the Visual Basic command
     MsgBox to display a Message Box containing the text string.


RUNNING THE PROGRAM

     You can execute the program from within Visual Basic by clicking the Start button
     from the Standard Toolbar. You should see a Window that appears
     something like Figure 1.21.




        FIGURE 1.21 Your first program running inside the IDE.
                                                       Introduction to Visual Basic   19


        You can close it like any Windows program by clicking the X button on the
    Title Bar or by selecting the Stop button on the Standard Toolbar from within the
    Visual Basic IDE.
        You’ve created your first program. You can save it if you would like, by choos-
    ing Save from the File Menu. When you save a project, it’s best to create a new
    directory in which you can store all the files necessary for the project. In this way,
    you keep the files in one easy to manage area without the risk of another project
    corrupting the source code or data.


COMPLETE CODE LISTING

    The following code is the complete listing for this chapter:

        Private Sub Command1_Click()
        Dim strInfo As String
          strInfo = "My first Visual Basic program."
          MsgBox strInfo
        End Sub


        Private Sub Form_Load()
          Text1.Text = "Click the button to display a message"
        End Sub




CHAPTER REVIEW

    During the first chapter, we looked at numerous concepts, many of which might be
    new. You discovered the Windows, Toolbars, Menus, and Objects that make up the
    Visual Basic IDE and how to interact with many of them. Visual Basic.NET
    provides a variety of new features. As a result, Visual Basic 6 projects need to be
    upgraded by the Upgrade Wizard before they can be used. Lastly, you developed a
    simple application by using a few intrinsic Controls and some basic code, and then
    proceeded to run it inside the Visual Basic IDE.
        Now that you have some of the basics out of the way, let’s move to the next
    chapter where the real fun begins!

								
To top