Visual Basic Book 1

Embed Size (px)

Citation preview

  • 7/29/2019 Visual Basic Book 1

    1/20

    Although this book is based around developing projects, it is important to haveat 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 yourfirst Visual Basic program. Topics that youll be exposed to include the basics of theVisual Basic language, variables, the built-in components, the ingredients that makeup a basic application and the Integrated Development Environment (IDE).

    1 Introduction to Visual Basic

    1

  • 7/29/2019 Visual Basic Book 1

    2/20

    The vast majority of screen shots and information pertain to the Visual Basic 6IDE. However, this chapter addresses the differences in the Visual Basic 6 andVisual Basic.NET IDEs and includes information on how to open and convert version6 projects to .NET.

    For those of you already familiar with Visual Basic, you can feel free to moveahead to Chapter 2 where we will begin working on a multimedia and audio CDplayer. However, if you are a beginner or an intermediate programmer, this chapterwill build a solid foundation onto which you can base your future Visual Basiclearning.

    The Integrated Development Environment

    The Visual Basic Integrated Development Environment (IDE) may be the singlebiggest reason for the vast popularity of Visual Basic. It provides everything youneed 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 theWindows Start menu the exact path required to access this shortcut is dependentupon your installation and may differ on individual machines. Another option is tocreate 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 isinstalled, you can also run it by double-clicking on files that end with a vpb (VisualBasic Project) extension.

    When you open Visual Basic, youre presented with an opening screen that will

    appear very much like Figure 1.1. For most of the projects in this book, you will becreating Standard EXE files, so you should click the Open button or just press theEnter key. This standard type of project will create a standard Windows executableprogram that can be run outside of the IDE.

    As you can see in Figure 1.2, the Visual Basic IDE is fundamentally a collectionof Menus, Toolbars, and Windows that come together to form the GUI. There arefive main Windows that appear in the default Visual Basic IDE, along with theStandard Toolbar, Menu Bar, and Title Bar.

    If you have ever used VB5, the version 6 IDE will look very similar to you. Infact, 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 Basicversion 4 or earlier, the IDE may take some getting used to, as Visual Basic 5 and 6have been changed to a Multiple Document Interface (MDI) application. If you arenew to Visual Basic, the IDE can seem a little daunting at first glance. However, thiswill quickly fade away as you begin to become comfortable with each part.

    2 Learning Visual Basic Through Applications

  • 7/29/2019 Visual Basic Book 1

    3/20

    Introduction to Visual Basic 3

    FIGURE 1.1The 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.

  • 7/29/2019 Visual Basic Book 1

    4/20

    The Title Bar and Menu Bar

    As you can see in Figure 1.3, the Visual Basic IDE contains a Menu Bar and Title Barthat appears very similar to most Windows applications. The Title Bar serves as aquick reminder of what you are doing inside the IDE. For instance, unless you have

    changed something, the Title Bar should currently read Project 1 MicrosoftVisual Basic [design].

    4 Learning Visual Basic Through Applications

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

    FIGURE 1.4 Toolbars provide shortcuts to many of the common functions.

    The Menu Bar provides functions that you would expect from any standard

    Windows application. For instance, the File Menu allows you to Load and Saveprojects; the Edit Menu provides Cut, Copy, and Paste Commands that are familiarto most Windows users; and the Window Menu allows you to open and closeWindows inside the IDE. Each Menu Option works like it would in any otherWindows application, so they dont need any real introduction. You shouldnt beoverly concerned with all of the options at this time, because well be spendingsome 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 theone found in the vast majority of Windows applications. It provides shortcuts tomany of the commonly used functions provided by Visual Basic and along with theStandard Toolbar, Microsoft has provided several additional built-in Toolbars thatcan make your job a little easier. To add or remove any of the Toolbars, you canright-click on the Menu Bar, or you can select Toolbars from the View Menu.

  • 7/29/2019 Visual Basic Book 1

    5/20

    Individual Toolbars

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

    Introduction to Visual Basic 5

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

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

    FIGURE 1.7 The Form Editor Toolbar displays Buttons

    specific to Form editing features.

    The Edit Toolbar

    In Figure 1.6, you will find the Edit Toolbar, which can be useful when youre

    editing code and setting breakpoints and bookmarks. This Toolbar containsCommands that can be located in the Edit Menu.

    The Form Editor Toolbar

    The Form Editor Toolbar (see Figure 1.7) includes most of the Commands in theFormat Menu and is useful only when youre arranging Controls on a Forms surface.

    Whether you decide to display these Toolbars is purely a matter of personaltaste, as the functions they provide are generally available in Menu Options. Severalfactors, such as your screen size and resolution, may make their use impractical.

  • 7/29/2019 Visual Basic Book 1

    6/20

    You can create a custom Toolbar or customize the appearance of the built-inToolbars by following a couple of steps. First, right-click on any Toolbar, and thenselect the Customize option. From the Customize Window that appears, click theNew 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 theCommands Tab, which displays a list of available Menu Commands. From the listof categories and Commands, select the options you would like to have on yourToolbar. The changes are automatically saved, so continue placing options on theToolbar 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 tobecome familiar with in order to get a basic grasp of the Visual Basic IDE. The FormWindow displays the basic building block of Visual Basic applications. The CodeWindow is where you enter code for your application. The Toolbox Windowdisplays some of the built-in Visual Basic Controls. You can set properties of thecomponents and Forms with the Properties Window. Lastly, the Project Explorerdisplays the Objects that make up the project you are working on and you canposition and view the Forms with the Form Layout Window.

    6 Learning Visual Basic Through Applications

    FIGURE 1.8 Standard Controls, as well as

    ActiveX Controls, are displayed in the Toolbox.

    The Toolbox

    The Toolbox, which can be seen inFigure 1.8, is probably the Windowthat you will become familiar with thequickest, as it provides access to all ofthe standard Controls that residewithin the Visual Basic runtime itself.These Controls, known as intrinsicControls, cannot be removed fromthe Toolbox, and include the following

    options.

  • 7/29/2019 Visual Basic Book 1

    7/20

    Pointer: The pointer is the only item on the Toolbox that isnt 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 havea need to be edited by an end user. Its often displayed next to additionalControls such as Text Boxes to label their use.

    TextBox: You use Text Box Controls for user input. It may be the most widelyused 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 outsideof it, and if the Frame is moved on the Form, the Controls are moved with it.

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

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

    OptionButton: The Option Button Control is similar to the Check Box Controlin that it offers the ability to select an option. However, an Option ButtonControl is most often used when a group of options exists and only one itemcan 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 toselect one or more items.

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

    ScrollBars: The HScrollBar and VScrollBar Controls let you create scroll barsbut are used infrequently because many Controls provide the ability to displaytheir own Scroll Bars.

    Introduction to Visual Basic 7

  • 7/29/2019 Visual Basic Book 1

    8/20

    Timer: The Timer Control is an oddity when it is compared to other Controls,in that it isnt displayed at runtime. Its used to provide timed functions forcertain events.

    DriveListBox, DirListBox, FileListBox: These Controls can be used individually,but many times are used together to provide dialog boxes (also known as windowsin 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 PictureBox Control, and although it doesnt provide all of the functionality that thePicture 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 moreControls on a Form to fields in a database.

    OLE: The OLE (Object Linking and Embedding) Control can host Windowsbelonging to other executable programs. For instance, you can use it to displaya 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, andLabel Controls are used in almost all Visual Basic developed applications. Whilesome Controls are very important, others may provide functionality that can bereplaced by far superior Controls. For instance, you probably shouldnt use theData Control, as it cannot be used with ActiveX Data Objects (ADO) data sources.

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

    8 Learning Visual Basic Through Applications

  • 7/29/2019 Visual Basic Book 1

    9/20

    Form Window

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

    Code Window

    Every Form has a Code Window, which is where you write the code for yourprogram. 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 asample Code Window.

    Introduction to Visual Basic 9

    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.

  • 7/29/2019 Visual Basic Book 1

    10/20

    10 Learning Visual Basic Through Applications

    Project Explorer

    The Project Explorer can be seen in Figure 1.11 and is provided to help youmanage projects. The Project Explorer is a hierarchical tree-branch structure thatdisplays 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 youcan simply double-click on the part of the project you would like to work on. Forinstance, if you have a project with several Forms, you can simply double-click theparticular Form you want to view.

    FIGURE 1.11 Youll quickly realize

    the usefulness of the Project Explorer.

    FIGURE 1.12 Pop-up Context Menus

    make available countless valuable

    features in the IDE.

    You can also display the Project Explorer at any time by pressing the F4 key. Youcan 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 withit by clicking on the Code Window icon that is displayed at the upper left side of theProject Explorer.

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

  • 7/29/2019 Visual Basic Book 1

    11/20

    Properties Window

    The Properties Window is used for the configuration of the Controls you place ona Form, as well as the Form itself. All of the standard Visual Basic Controls haveproperties, and the majority of ActiveX Controls do as well. As you can see inFigure 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 youdesign an application, or you can alter them in code.

    Introduction to Visual Basic 11

    FIGURE 1.13 The Properties Window allows you to

    adjust properties for many Visual Basic Objects.

    FIGURE 1.14 You can change the

    position of executed Forms with the

    Form Layout Window.

    Form Layout Window

    The Form Layout Window is visible in Figure 1.14. Its only purpose is to allow youto set the position of Forms when they are actually being executed duringruntime. The process is very simple. You select the position of the Form by movingit 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 notaffect its position during runtime execution.

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

  • 7/29/2019 Visual Basic Book 1

    12/20

    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 introducessome changes to the IDE and new Windows Forms and Web Forms. The producthas truly been developed from the ground up and is not just an upgrade to Visual Basic 6.

    12 Learning Visual Basic Through Applications

    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 needto be upgraded before it can be used. Fortunately, the vast majority of time, this isvery easy as it happens automatically when you open a Visual Basic 6 project inVisual Basic.NET. An Upgrade Wizard, which can be seen in Figure 1.16, steps youthrough the upgrade process and creates a new Visual Basic.NET project. Theexisting Visual Basic 6 project is left unchanged. If you have Visual Basic version 5

  • 7/29/2019 Visual Basic Book 1

    13/20

    Depending on your application, you may need to make minor changes to your codeafter it is upgraded. Many times this can be necessary because certain features eitherare 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 reportto help you make changes and review the status of your project. The items aredisplayed as tasks in the new Task List Window, so you can easily see what changesare required, and so you can navigate to the code statement simply by double-clicking the task. Many times, the document recommendations simply representgood programming practices, but they also identify the Visual Basic 6 Objects andmethods 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 IDEs can be used on the same computerand can even execute simultaneously. Additionally, applications written andcompiled in Visual Basic.NET and Visual Basic 6.0 can be installed and executed onthe same computer. Although the projects in this book have been written for VisualBasic 5 or 6, they should work equally well with Visual Basic.NET.

    Introduction to Visual Basic 13

    FIGURE 1.16 The Upgrade Wizard makes it easy

    to convert version 6 projects to Visual Basic.NET.

    projects, its 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 syntaxchanges and your Visual Basic 6.0 Forms are converted to Windows Forms.

  • 7/29/2019 Visual Basic Book 1

    14/20

    A QUICK PROJECT

    Now that you have an understanding of the Visual Basic IDE, you can put theinformation 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 youll take when you are developingan application. Start the Visual Basic IDE using one of the methods that werementioned previously in the chapter and select Standard EXE from the firstWindow that appears and click the Open button.

    The next step is to place Controls on the default Form that appears. There aretwo separate approaches you can use to do this. First, you can simply double-clickon 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 thepointer 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 youdrag 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.

    14 Learning Visual Basic Through Applications

    FIGURE 1.17 You can place Controls on a

    Form in several different ways.

    You dont have to place Controls precisely where you want them, as you canmove them as Visual Basic provides the necessary tool to reposition them at anytime during the development process. To move a Control you have created with

  • 7/29/2019 Visual Basic Book 1

    15/20

    Introduction to Visual Basic 15

    FIGURE 1.18 Handles are useful resizing Objects.

    FIGURE 1.19 Beginnings of a GUI.

    either process, click the Object (anywhere on the Object except the edges) in theForm Window and drag it, releasing the mouse button when you have it in thecorrect location. You can resize a Control very easily as well, by clicking the Objectso 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.

    For a first project, you can begin by placing a Text Box and a CommandButton on the Form and positioning them so that they look something like Figure1.19.

  • 7/29/2019 Visual Basic Book 1

    16/20

    The next step is to double-click the Command Button on the Form, which willbring up the Code Window and leave you something that looks similar to Figure1.20. Its worth noting that your window will currently only have the Private SubCommand_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, aCommand Buttons Click Event is its most popular so Visual Basic automaticallyplaces the lines in the Code Window.

    16 Learning Visual Basic Through Applications

    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 Basicmay 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 surethat you declare all of your variables and is used by default throughout the book.If you dont use the option explicit statement, all undeclared variables are treatedas 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 theRequire 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

  • 7/29/2019 Visual Basic Book 1

    17/20

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

    Private Sub Command1_Click()

    Dim strInfo As StringstrInfo = "My first Visual Basic program."

    MsgBox strInfo

    End Sub

    From the drop down Menu located at the top left of the Code Window, selectForm. A Form _Load event procedure is created for you automatically. Enter thefollowing 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 eachof the projects well create throughout the book. This saves you time and program-ming mistakes, which will allow you to focus only on the task at handlearningVisual Basic. It also contains several applications. Please see the CD-ROM for acomplet list of applications and compiled applications.

    THE CODE EXPLANATION

    Thats all we need for this application. Although this project is very simple, you aregoing to be introduced to a few items that you wouldnt necessarily need for thiseasy of an application, but they are being presented in order to get you started inVisual Basic development. The first of these extras are variables, which are used byVisual Basic to hold information needed by your application. There are only a fewsimple rules you should keep in mind when you use variables. They should be lessthan 40 characters; they can include letters, numbers, and underscores (_); theycannot use one of the Visual Basic reserved words (i.e. you cannot name a variableText); and they have to begin with a letter.

    Lets look carefully at what the code you typed does. The Private SubCommand1_Click() tells Visual Basic to run this line of code when someone clickson the Command Button you created called Command1. When they do click theCommand Button, the lines of code you typed in are executed. The End Sub

    Introduction to Visual Basic 17

  • 7/29/2019 Visual Basic Book 1

    18/20

    simply informs Visual Basic that its time to stop running the code. The Private Suband End Sub lines were created automatically for you when you double-clicked onthe 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 addeda line that sets the Text Box equal to Click the button to display a message. Likethe Command1_Click event, the code is run only when something occurs, which inthis 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 dimensionsthe variable strInfo as a string. The next line assigns the text string My first VisualBasic program to the variable and the final line uses the Visual Basic commandMsgBox 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 buttonfrom the Standard Toolbar. You should see a Window that appearssomething like Figure 1.21.

    18 Learning Visual Basic Through Applications

    FIGURE 1.21 Your first program running inside the IDE.

  • 7/29/2019 Visual Basic Book 1

    19/20

    You can close it like any Windows program by clicking the X button on theTitle Bar or by selecting the Stop button on the Standard Toolbar from within theVisual Basic IDE.

    Youve 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, its best to create a newdirectory 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 projectcorrupting 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 benew. You discovered the Windows, Toolbars, Menus, and Objects that make up theVisual Basic IDE and how to interact with many of them. Visual Basic.NETprovides a variety of new features. As a result, Visual Basic 6 projects need to beupgraded by the Upgrade Wizard before they can be used. Lastly, you developed asimple application by using a few intrinsic Controls and some basic code, and thenproceeded to run it inside the Visual Basic IDE.

    Now that you have some of the basics out of the way, lets move to the nextchapter where the real fun begins!

    Introduction to Visual Basic 19

  • 7/29/2019 Visual Basic Book 1

    20/20