Visual basic 5 Apostila

Embed Size (px)

Citation preview

  • 8/9/2019 Visual basic 5 Apostila

    1/641

    Programmer’s Guide VB 5.0

    Welcome to the Visual Basic® Programmer?s Guide, a comprehensive manual on

    programming with Visual Basic. To accommodate the wealth of features and capabilities

    in Visual Basic 5.0, the Programmer?s Guide is divided into two parts.

    The first part covers the basic concepts, providing a foundation for programmers new to

    Visual Basic. Part 2 covers more advanced programming concepts and techniques.

    Additional information helpful in using the product is presented in the appendices.

  • 8/9/2019 Visual basic 5 Apostila

    2/641

    Index

    Part 1 

    An introduction to programming in Visual Basic.

    Part 2

    Advanced topics on Visual Basic programming.

    Appendix A

    Technical details for Visual Basic 5.0.

    Appendix B

    Suggested guidelines for consistent and readable code.

    Appendix C

    Details on command line switches for compiling to native code.

  • 8/9/2019 Visual basic 5 Apostila

    3/641

    Part 1

    Visual Basic Basics

    Many of the things that you can do with Visual Basic really aren?t very basic at all. The Visual Basic language is quitepowerful - if you can imagine a programming task, it can probably be accomplished using Visual Basic. As you might guess,there?s a lot to be learned before you can consider yourself a guru; but once you understand the basics of Visual Basic you?llfind that you are productive in no time at all.

    The first five chapters of the Visual Basic Programmer?s Guide cover the basics, providing the foundation that you will needfor anything you want to do in Visual Basic.

    Chapter 1 Introducing Visual Basic 5.0

    Explains how to install Visual Basic and get assistance while you work.

    Chapter 2 Developing an Application in Visual Basic

    An introduction to the integrated development environment and the process of creating your first application.

    Chapter 3 Forms, Controls, and Menus

    An introduction to the objects that you can put together to create an application.

    Chapter 4 Managing Projects

    An introduction to the tools used to organize your work in Visual Basic.

    Chapter 5 Programming Fundamentals

    An introduction to the nuts and bolts of the Visual Basic language.

  • 8/9/2019 Visual basic 5 Apostila

    4/641

    Part 2

    What Can You Do With Visual Basic?

    Once you understand the basics of working with Visual Basic, you?re ready to move on to new and bigger challenges. So,what can you do with Visual Basic? It might be more appropriate to ask what can?t be done. The answer is: not much! Fromdesigning innovative user interfaces to taking advantage of other application?s objects, from manipulating text and graphicsto working with databases, Visual Basic provides the tools that you?ll need to get the job done right.

    Part 1 of the Programmer’s Guide provided the foundation; Part 2 provides the bricks and mortar to build upon thatfoundation to create increasingly complex applications with Visual Basic.

    Chapter 6 Creating a User Interface

    In-depth coverage of interface styles, forms, menus, toolbars, and more.

    Chapter 7 Using Visual Basic’s Standard Controls

    Covers Visual Basic’s intrinsic controls and how you can use them.

    Chapter 8 More About Programming

    A discussion of more programming concepts, techniques, and additional tools available in Visual Basic.

    Chapter 9 Programming with Objects

    In-depth coverage of objects, including creating classes and using ActiveX Designers.

    Chapter 10 Programming with Components

    Covers techniques for using ActiveX components in your own applications.

    Chapter 11 Responding to Mouse and Keyboard Events

    A discussion of processing user input, including drag and drop.

    Chapter 12 Working with Text and Graphics

    Explains how to use Visual Basic?s text and graphics methods for display and printing.

    Chapter 13 Debugging Your Code and Handling Errors

    Explains what to do when something doesn?t works as planned, either at design time or run time.

    Chapter 14 Accessing Data

    Techniques for working with databases and processing files.

    Chapter 15 Designing for Performance and Compatibility

    Optimization techniques to make your applications faster or smaller.

    Chapter 16 International Issues

  • 8/9/2019 Visual basic 5 Apostila

    5/641

    A discussion of considerations for multilingual and multicultural applications.

    Chapter 17 Distributing Your Application

    Explains how to use the Setup Wizard to create installation programs.

  • 8/9/2019 Visual basic 5 Apostila

    6/641

    Chapter 1.

    Introducing Visual Basic 5.0

    This chapter contains information on installing Microsoft Visual Basic on your system, adding or removing Visual Basiccomponents, using online Help, and resources for learning or getting additional help with Visual Basic.

    Contents

    Welcome to Visual BasicInstalling Visual BasicGetting Assistance While You Work

    Welcome to Visual Basic

    Welcome to Microsoft Visual Basic, the fastest and easiest way to create applications for Microsoft Windows®. Whether youare an experienced professional or brand new to Windows programming, Visual Basic provides you with a complete set of tools to simplify rapid application development.

    So what is Visual Basic? The "Visual" part refers to the method used to create the graphical user interface (GUI). Rather thanwriting numerous lines of code to describe the appearance and location of interface elements, you simply drag and dropprebuilt objects into place on screen. If you’ve ever used a drawing program such as Paint, you already have most of theskills necessary to create an effective user interface.

    The "Basic" part refers to the BASIC (Beginners All-Purpose Symbolic Instruction Code) language, a language used by moreprogrammers than any other language in the history of computing. Visual Basic has evolved from the original BASIClanguage and now contains several hundred statements, functions, and keywords, many of which relate directly to theWindows GUI. Beginners can create useful applications by learning just a few of the keywords, yet the power of thelanguage allows professionals to accomplish anything that can be accomplished using any other Windows programming

    language.

    The Visual Basic programming language is not unique to Visual Basic. The Visual Basic programming system, ApplicationsEdition included in Microsoft Excel, Microsoft Access, and many other Windows applications uses the same language. TheVisual Basic programming system, Scripting Edition (VBScript) for Internet programming is a subset of the Visual Basiclanguage. The investment you make in learning Visual Basic will carry over to these other areas.

    Whether your goal is to create a small utility for yourself or your work group, a large enterprise-wide system, or evendistributed applications spanning the globe via the Internet, Visual Basic has the tools you need.

    Data access features allow you to create databases and front-end applications for most popular database formats,including Microsoft SQL Server and other enterprise-level databases.

    ActiveX™ technologies allow you to use the functionality provided by other applications, such as Microsoft Word

    word processor, Microsoft Excel spreadsheet, and other Windows applications. You can even automate applicationsand objects created using the Professional or Enterprise editions of Visual Basic.Internet capabilities make it easy to provide access to documents and applications across the Internet from within yourapplication.Your finished application is a true .exe file that uses a run-time dynamic-link library (DLL) that you can freelydistribute.

    Visual Basic Editions

  • 8/9/2019 Visual basic 5 Apostila

    7/641

    Visual Basic is available in three versions, each geared to meet a specific set of development requirements.

    The Visual Basic Learning edition allows programmers to easily create powerful applications for Microsoft Windows95 and Windows NT®. It includes all intrinsic controls, plus grid, tab, and data-bound controls. Documentationprovided with the this edition includes Learn VB Now (a multimedia CD-ROM title), a printed Programmer’s Guide,online Help, plus Visual Basic Books Online.The Professional edition provides computer professionals with a full-featured set of tools for developing solutions for

    others. It includes all the features of the Learning edition, plus additional ActiveX controls, including Internet controls,and the Crystal Report Writer. Documentation provided with the Professional edition includes the Programmer’sGuide, online Help, the Component Tools Guide and the Crystal Reports for Visual Basic User’s Manual. The Enterprise edition allows professionals to create robust distributed applications in a team setting. It includes all thefeatures of the Professional edition, plus the Automation Manager, Component Manager, database management tools,the Microsoft Visual SourceSafe™ project-oriented version control system, and more. Printed documentationprovided with the Enterprise edition includes all Professional edition pieces, plus the Building Client/Server  Applications with Visual Basicbook and the SourceSafe User’s Guide.

    Installing Visual Basic

    You install Visual Basic on your computer using the Setup program. The Setup program installs Visual Basic itself, the Help

    system, sample applications, Visual Basic Books Online, and other product components from the CD-ROM to your harddisk.

    Important You cannot simply copy files from the CD-ROM to your hard disk and run Visual Basic. You must use the Setupprogram, which decompresses and installs the files in the appropriate directories.

     

    Before You Run SetupvbconBeforeYouRunSetup Things to check prior to installation.Setting Up Visual BasicvbconSettingUpVisualBasic Instructions for installing Visual Basic

    Before You Run Setup

    Before you install Visual Basic, make sure that your computer meets the minimum requirements, and read the Readme file,located at the root directory on your installation disk.

    Check the Hardware and System Requirements

    To run Visual Basic, you must have certain hardware and software installed on your computer. The system requirementsinclude:

    Microsoft Windows NT 3.51 or later, or Microsoft Windows 95.80486 or higher microprocessor.A hard disk with a minimum of 50 megabytes available space for a full installation.

    A CD-ROM disc drive.VGA or higher-resolution screen supported by Microsoft Windows.16 MB of RAM.A mouse or other suitable pointing device.

    For More Information For more details about requirements, see "System Requirements for Visual Basic" in Appendix A,"Visual Basic Specifications, Limitations, and File Formats."

    Read the Readme File

  • 8/9/2019 Visual basic 5 Apostila

    8/641

    The Readme file lists any changes to the Visual Basic documentation since its publication. It can be found by selecting ReadMe First from the initial setup screen, or in the root directory of the CD-ROM. Check the first section of the file for detailsand new information about installing Visual Basic.

    Setting Up Visual Basic

    When you run the Setup program, a directory is created for Visual Basic; you can then select the components of Visual Basicthat you want to install.

    With the exception of the operating system files in the \Os directory, files on the compact disc are not compressed, so they’reusable directly from the disc. For example, if you choose to not install Help files and Books Online on your hard drive, youcan still run them from Visual Basic. You’ll be able to press F1 and get appropriate Help messages - that is, context sensitivitywill work.

    To setup from compact disc

    1. Insert the compact disc in the CD-ROM drive.

    2. Use the appropriate command in your operating environment to run the setup program, which is available in the rootdirectory on the compact disc. If AutoPlay is enabled on your system, the setup program will automatically load whenyou insert the compact disc.

    3. Select Install Visual Basic 5.0.4. Follow the setup instructions on screen.

    For More Information See the Readme file for detailed instructions on installing Visual Basic.

    Adding or Removing Components of Visual Basic

    You can run Setup as many times as necessary. For example, you can run Setup to reinstall Visual Basic in another directory,or to install other portions of Visual Basic.

    To add or remove components of Visual Basic

    1. Insert the compact disc in the CD-ROM drive.2. Use the appropriate command in your operating environment to run the setup program, which is available in the root

    directory on the compact disc. If AutoPlay is enabled on your system, the setup program will automatically load whenyou insert the compact disc.

    3. Select the Custom button in the Microsoft Visual Basic 5.0 Setup dialog box.4. Select the components to be installed (or deselect the components to be removed) in the Options list box of the

    Custom dialog box.5. Follow the setup instructions on the screen.

    Starting Visual Basic

    Once you have completed the Setup procedure, you can start Visual Basic by using the Start button on the task bar inWindows 95. If AutoPlay is enabled on your system, you can also start Visual Basic by inserting the Visual Basic 5.0compact disc.

    For More information See Chapter 2, "Developing an Application in Visual Basic."

    Getting Assistance While You Work 

  • 8/9/2019 Visual basic 5 Apostila

    9/641

    The online documentation system references nearly all aspects of Visual Basic. It includes:

    Visual Basic Books Online, an online viewer displaying both print and online documents together in one window,accessed by a single multifeatured search engine.Online Help, containing extensive information on the Visual Basic programming environment and language.Visual Basic Online Links, providing pointers to sources of Visual Basic information on the World Wide Web.Microsoft Product Support Services, with information on obtaining technical support.

    Visual Basic Books OnlinevbconVisualBasicBooksOnline How to use Books Online.Online HelpvbconOnlineHelp An overview of the Online Help system.Context-Sensitive HelpvbconContextSensitiveHelp Getting help from within the integrated development environment.Visual Basic Online LinksvbconVisualBasicOnlineLinks Accessing additional information about Visual Basic.Microsoft Product Support ServicesvbconMicrosoftProductSupportServices Options for product support.

    Visual Basic Books Online

    Visual Basic Books Online contains all of the Visual Basic documentation in one location. Books Online also includesmultimedia demonstrations and topics that aren’t available in the printed documentation. You can find all the topics availableon any subject in Visual Basic documentation, print or online, with a single search.

    To start Visual Basic Books Online

    From the Help menu, select Books Online. Visual Basic Books Online is displayed, as shown in Figure 1.1.

    1. Figure 1.1 Visual Basic Books Online

    1.

    There are several ways you can look for information in Books Online.

    Using the table of contents. The contents pane presents a complete hierarchical list of books and topics. You can

    navigate this list just like you navigate the Explorer in Windows 95.Using the keyword index. You can choose from an alphabetical list much like search keywords in online Help.Using full-text search. You can type a word or phrase, or select a previous search string from the drop-down list. Youcan also use Boolean search operators.

    For More Information Details on using the Visual Basic Books Online browser are available by using Help in BooksOnline.

  • 8/9/2019 Visual basic 5 Apostila

    10/641

    Getting the Most Out of Books Online Content

    In addition to the features of its browser, the content of Books Online includes several features designed to make findinginformation easier.

    What’s New in Visual Basic 5.0?

    1. Use this section to go quickly to information on new and enhanced features of Visual Basic. Organized by featurecategory, it provides over 400 described links to more information.

    Find It Fast

    Use this section to sort out subject areas covered throughout the documentation. Debugging information, for example,comes in a variety of flavors, depending on the kind of project you’re working on. The described links in this sectionmake the search easier.

    Overview topics

    1. Use these to get information about topics in a book or chapter before you go to the topics themselves. By providing aglimpse of content in each topic, the described links in overviews at the head of books, parts, and chapters save time.

    Related Information links

    1. Use the Related Information button in the lower right corner of the browser to view the titles of topics you can go tofor more information. Topics listed here often contain information important to know before using the information inthe topic at hand.

    Microsoft Word documents and Word Viewer 7.1

    1. Use these to scroll, copy, and print many topics at once. Microsoft Word .doc files for all of the chapters in theProgrammer’s Guide, Component Tools Guide, Guide to Data Access Objects, and the Guide to BuildingClient/Server Applications with Visual Basic are included in the Tools directory on the Visual Basic CD-ROM. If youdon’t have Word, you can view and print the documents with Word Viewer, which you can install using the Setup.exeprogram also in Tools.

    Online Help

    You can access Help by choosing the Microsoft Visual Basic Help Topics command from the Help menu, by searching forspecific topics with the Search Reference Index? command, or by pressing F1 to get context-sensitive Help on the VisualBasic programming environment or keywords in the language.

    Help Contents

    For information on Help topics, choose Microsoft Visual Basic Help Topics from the Help menu or press F1 and click the

    Contents button. You can use the Contents tab (Figure 1.2) to get quick access to key reference topics.

    Figure 1.2 The Contents tab

  • 8/9/2019 Visual basic 5 Apostila

    11/641

    Help Search

    The fastest way to find a particular topic in Help is to use the Index tab in the Help dialog box (Figure 1.3). To display theHelp dialog box, you can either choose Search Reference Index from the Help menu or click the Help Topics button on anyHelp topic screen.

    Figure 1.3 The Index tab

    To search Help

    1. From the Help menu, choose Search Reference Index, or click the Help Topics button from any Help topic window.2. In the Search dialog box, type a word, or select one from the list by scrolling up or down. Press ENTER or choose

    Display to display a list of topics related to the word you specified.3. Select a topic name, and then press ENTER or choose Display to view the topic.

    Context-Sensitive Help

  • 8/9/2019 Visual basic 5 Apostila

    12/641

    Many parts of Visual Basic are context sensitive. Context sensitive means you can get Help on these parts directly withouthaving to go through the Help menu. For example, to get Help on any keyword in the Visual Basic language, place theinsertion point on that keyword in the Code window and press F1.

    You can press F1 from any context-sensitive part of the Visual Basic interface to display Help information about that part.The context-sensitive parts are:

    Every window in Visual Basic (Properties window, Code window, and so on)Controls in the ToolboxObjects on a form or document objectProperties in the Properties windowEvent procedures in the Code windowVisual Basic keywords (statements, functions, properties, methods, events, and special objects)Error messages

    Once you’ve opened Help, you can press F1 for information about how to use Help itself.

    Running Code Examples from Help

    Many of the language topics in Help contain code examples that you can run from Visual Basic. The following proceduresshow you how to copy and run a code example from Help.

    Note The following procedure is for code examples that do not contain public declarations.

    To copy a code example from Help

    1. Create a new form by choosing Add Form from the Project menu, or use an existing form. (For more information oncreating and using forms, see Chapter 2, "Developing An Application in Visual Basic.")

    2. Choose Search Reference Index from the Help menu.3. In Help, search for graphics, and go to the topic called "FillColor Property."4. In the FillColor Property topic, click the Example jump, located in the nonscrolling region near the top of the window.

    (A  jump is a word that you can click to go to another topic. Jumps are underlined and the jump text is green.)5. Select the subroutine portion of the example. Note that the first "Sub" marks the beginning of the procedure and the

    last "End Sub" marks the end of the procedure, as shown in Figure 1.4.

    1. Figure 1.4 Selecting the procedure portion of the example

    1.

  • 8/9/2019 Visual basic 5 Apostila

    13/641

    7. Right-click the selected text and select Copy from the context menu. The text is copied onto the Clipboard.8. Return to the form you created and double-click the form to display the Code window.9. Place the insertion point below any existing code in the Code window.9. From the Edit menu, choose Paste. The example now appears in the Code window.

    10. From the Run menu, choose Start, or press F5.12. Click the form to run the example code.

    Note Some code examples require you to draw controls on the form. For more information on drawing controls, see Chapter3, "Forms, Controls, and Menus."

    Visual Basic Online Links

    If you have a modem or other means of access, additional information about Visual Basic is available on the World WideWeb.

    Microsoft Web Site

    The Microsoft World Wide Web site contains several areas of interest to Visual Basic programmers. The Visual Basic homepage is located at http://www.microsoft.com/vbasic/. Information available at this site includes:

    The Visual Basic Knowledge Base, containing "how-to" articles about Visual Basic, reports on known bugs and bugfixes, and other informational topics.The Visual Basic Software Library, containing updates to program files, help updates, drivers, and other Visual Basicrelated files.Visual Basic Frequently Asked Questions, containing answers to the questions most frequently asked of ProductSupport Services.

    To access the Microsoft Visual Basic Web site

    1. Choose Microsoft on the Web from the Help menu.2. Select the appropriate option from the submenus.

    Note You must have a Web browser installed and you must be connected to the Internet for these options to work. Some of the content on the Microsoft Web site is optimized for Microsoft Internet Explorer and may not be fully visible to lessadvanced browsers. You can download the latest version of Internet Explorer from the Web site.

    Other Online Resources

    Forums for Visual Basic programmers are also available on the Microsoft Network, CompuServe, and America Online.These forums typically contain libraries of sample applications and ActiveX controls, as well as discussion groups forobtaining peer support. For details on connecting to these services, see Obtaining Technical Support under the Visual BasicHelp menu.

    Microsoft Product Support Services

  • 8/9/2019 Visual basic 5 Apostila

    14/641

    Microsoft offers a variety of support options to help you get the most from Visual Basic.

    If you have a question about the product, first look in the print documentation, or consult online Help. If you can’t find theanswer, contact Microsoft Product Support Services.

    Support services are available both within the United States and through subsidiary offices worldwide. For complete details,see Obtaining Technical Support under the Visual Basic Help menu.

    Tell Us What You Think

    Microsoft is committed to providing the best possible products to our customers. With each new version, Visual Basic hasevolved in order to meet the changing needs of Windows programmers.

    We’re always interested in hearing from our customers. If you have any suggestions or comments regarding improvements orfeatures that you would like to see in future versions of Visual Basic, let us know. You can send your suggestions via e-mailto [email protected], by entering them on the Feedback Web page(http://www.microsoft.com/vbasic/vbinfo/vbfeed.htm), or by calling (206) 936-WISH.

  • 8/9/2019 Visual basic 5 Apostila

    15/641

  • 8/9/2019 Visual basic 5 Apostila

    16/641

    As you might imagine, dealing with all of the possible combinations of windows, events and messages could bemind-boggling. Fortunately, Visual Basic insulates you from having to deal with all of the low-level message handling. Manyof the messages are handled automatically by Visual Basic; others are exposed as Event procedures for your convenience.This allows you to quickly create powerful applications without having to deal with unnecessary details.

    Understanding the Event-Driven Model

    In traditional or "procedural" applications, the application itself controls which portions of code execute and in whatsequence. Execution starts with the first line of code and follows a predefined path through the application, callingprocedures as needed.

    In an event-driven application, the code doesn’t follow a predetermined path - it executes different code sections in responseto events. Events can be triggered by the user’s actions, by messages from the system or other applications, or even from theapplication itself. The sequence of these events determines the sequence in which the code executes, thus the path through theapplication’s code differs each time the program runs.

    Because you can’t predict the sequence of events, your code must make certain assumptions about the "state of the world"when it executes. When you make assumptions (for example, that an entry field must contain a value before running aprocedure to process that value), you should structure your application in such a way as to make sure that the assumption willalways be valid (for example, disabling the command button that starts the procedure until the entry field contains a value).

    Your code can also trigger events during execution. For example, programmatically changing the text in a text box cause thetext box’s Change event to occur. This would cause the code (if any) contained in the Change event to execute. If youassumed that this event would only be triggered by user interaction, you might see unexpected results. It is for this reason thatit is important to understand the event-driven model and keep it in mind when designing your application.

    Interactive Development

    The traditional application development process can be broken into three distinct steps: writing, compiling, and testing code.Unlike traditional languages, Visual Basic uses an interactive approach to development, blurring the distinction between thethree steps.

    With most languages, if you make a mistake in writing your code, the error is caught by the compiler when you start to

    compile your application. You must then find and fix the error and begin the compile cycle again, repeating the process foreach error found. Visual Basic interprets your code as you enter it, catching and highlighting most syntax or spelling errorson the fly. It’s almost like having an expert watching over your shoulder as you enter your code.

    In addition to catching errors on the fly, Visual Basic also partially compiles the code as it is entered. When you are ready torun and test your application, there is only a brief delay to finish compiling. If the compiler finds an error, it is highlighted inyour code. You can fix the error and continue compiling without having to start over.

    Because of the interactive nature of Visual Basic, you’ll find yourself running your application frequently as you develop it.This way you can test the effects of your code as you work rather than waiting to compile later.

    Elements of the Integrated Development Environment

    The working environment in Visual Basic is often referred to as the integrated development environment or IDEbecause it integrates many different functions such as design, editing, compiling, and debugging within a commonenvironment. In most traditional development tools, each of these functions would operate as a separate program, each

    with its own interface. 

    Starting the Visual Basic IDE

  • 8/9/2019 Visual basic 5 Apostila

    17/641

    When you run the Visual Basic Setup program, it allows you to place the program items in an existing program group orcreate a new program group and new program items for Visual Basic in Windows. You are then ready to start Visual Basicfrom Windows.

    To start Visual Basic from Windows

    1. Click Start on the Task bar2. Select Programs, and then Visual Basic 5.0.

    1. or

    1. Click Start on the Task bar.

    1. Select Programs.

    1. Use the Windows Explorer to find the Visual Basic executable file (VB5.exe).

    1. Double-click the Visual Basic icon.

    You can also create a shortcut to Visual Basic, and double-click the shortcut.

    When you first start Visual Basic, you see the interface of the integrated development environment, as shown in Figure 2.1.

    Figure 2.1 The Visual Basic integrated development environment

    Integrated Development Environment Elements

    The Visual Basic integrated development environment (IDE) consists of the following elements.

    Menu Bar

  • 8/9/2019 Visual basic 5 Apostila

    18/641

    Displays the commands you use to work with Visual Basic. Besides the standard File, Edit, View, Window, and Help menus,menus are provided to access functions specific to programming such as Project, Format, or Debug.

    Context Menus

    Contain shortcuts to frequently performed actions. To open a context menu, click the right mouse button on the object you’re

    using. The specific list of shortcuts available from context menus depends on the part of the environment where you click theright mouse button. For example, the context menu displayed when you right click on the Toolbox lets you display theComponents dialog box, hide the Toolbox, dock or undock the Toolbox, or add a custom tab to the Toolbox.

    Toolbars

    Provide quick access to commonly used commands in the programming environment. You click a button on the toolbar onceto carry out the action represented by that button. By default, the Standard toolbar is displayed when you start Visual Basic.Additional toolbars for editing, form design, and debugging can be toggled on or off from the Toolbars command on theView menu.

    Toolbars can be docked beneath the menu bar or can "float" if you select the vertical bar on the left edge and drag it awayfrom the menu bar.

    Toolbox

    Provides a set of tools that you use at design time to place controls on a form. In addition to the default toolbox layout, youcan create your own custom layouts by selecting Add Tab from the context menu and adding controls to the resulting tab.

    For More Information To learn more about specific controls, see Chapter 3, "Forms, Controls, and Menus" and Chapter 7,"Using Visual Basic’s Standard Controls." For information on how to add controls to the Toolbox, see "Adding Controls to aProject" in Chapter 4, "Managing Projects."

    Project Explorer Window

    Lists the forms and modules in your current project. A project  is the collection of files you use to build an application.

    For More Information For information on projects, see Chapter 4, "Managing Projects."

    Properties Window

    Lists the property settings for the selected form or control. A  property is a characteristic of an object, such as size, caption, orcolor.

    For More Information For information on properties, see "Understanding Properties, Methods, and Events" in Chapter 3,"Forms, Controls, and Menus."

    Object Browser

    Lists objects available for use in your project and gives you a quick way to navigate through your code. You can use theObject Browser to explore objects in Visual Basic and other applications, see what methods and properties are available forthose objects, and paste code procedures into your application.

    For More Information For more information on using the Object Browser to view procedures, see "Finding Out AboutObjects" in Chapter 9, "Programming with Objects." For details on using add-ins to extend the Visual Basic programmingenvironment, see "Using Wizards and Add-ins" in Chapter 4, "Managing Projects."

  • 8/9/2019 Visual basic 5 Apostila

    19/641

    Form Designer

    Serves as a window that you customize to design the interface of your application. You add controls, graphics, and pictures toa form to create the look you want. Each form in your application has its own form designer window.

    For More Information To learn how to add controls to an application, see "Your First Visual Basic Application" later in this

    chapter. To learn more about designing an interface, see Chapter 6, "Creating a User Interface."

    Code Editor Window

    Serves as an editor for entering application code. A separate code editor window is created for each form or code module inyour application.

    For More Information To learn more about entering code and using the code editor, see Chapter 5, "ProgrammingFundamentals."

    Form Layout Window

    The Form Layout window (Figure 2.2) allows you to position the forms in your application using a small graphicalrepresentation of the screen.

    Figure 2.2 The Form Layout window

    Immediate, Locals, and Watch Windows

    These additional windows are provided for use in debugging your application. They are only available when you are runningyour application within the IDE.

    For More Information To learn more about debugging and using the debug windows, see Chapter 13, "Debugging YourCode and Handling Errors."

    Note You can also add features to the Visual Basic interface by using a program called an add-in. Add-ins, which areavailable from Microsoft and third-party developers, can provide features like source code control, which allows you tosupport group development projects.

    Environment Options

    Visual Basic provides a great deal of flexibility, allowing you to configure the working environment to best suit yourindividual style. You can choose between a single or multiple document interface, and you can adjust the size and positioningof the various Integrated Development Environment (IDE) elements. Your layout will persist between sessions of VisualBasic.

    SDI or MDI Interface

    Two different styles are available for the Visual Basic IDE: single document interface (SDI) or multiple document interface

  • 8/9/2019 Visual basic 5 Apostila

    20/641

    (MDI). With the SDI option, all of the IDE windows are free to be moved anywhere on screen; as long as Visual Basic is thecurrent application, they will remain on top of any other applications. With the MDI option, all of the IDE windows arecontained within a single resizable parent window.

    To switch between SDI and MDI modes

    1. Select Options from the Tools menu.

    1. The Options dialog box is displayed.

    1. Select the Advanced tab.2. Check or uncheck the SDI Development Environment check box.

    1. The IDE will start in the selected mode the next time you start Visual Basic.

    1. or

    1. Run Visual Basic from the command line with a /sdi or /mdi parameter.

    Docking Windows

    Many of the windows in the IDE can be docked, or connected, to each other or to the edge of the screen. These include theToolbox, Form Layout Window, Project Explorer, Properties window, Color Palette, and Immediate, Locals, and Watchwindows.

    With the MDI option, windows can be docked to any side of the parent window; with SDI they can only be docked beneaththe menu bar. Docking capabilities can be toggled on or off for a given window by selecting the appropriate check box on theDocking tab of the Options dialog box, available from the Options command on the Tools menu.

    To dock or undock a window

    1. Select the window you wish to dock or undock.2. Drag the window to the desired location by holding down the left mouse button.

    The outline of the window will be displayed as you drag.

    3. Release the mouse button.

    Your First Visual Basic Application

    Creating an application in Visual Basic is simple. How simple? For the answer, try out the Hello, Visual Basic and Firstappapplications that follow.

    Hello, Visual Basic

    There are three main steps to creating an application in Visual Basic:

    1. Create the interface.2. Set properties.3. Write code.

    To see how this is done, use the steps in the following procedures to create a simple application that consists of a text box anda command button. When you click the command button, the message "Hello, world!" appears in the text box.

  • 8/9/2019 Visual basic 5 Apostila

    21/641

    Creating the Interface

    Forms are the foundation for creating the interface of an application. You can use forms to add windows and dialog boxes toyour application. You can also use them as containers for items that are not a visible part of the application’s interface. Forexample, you might have a form in your application that serves as a container for graphics that you plan to display in other

    forms.

    The first step in building a Visual Basic application is to create the forms that will be the basis for your application’sinterface. Then you draw the objects that make up the interface on the forms you create. For this first application, you’ll usetwo controls from the Toolbox.

    Button Control

    Text box

    Command button

    To draw a control using the Toolbox

    1. Click the tool for the control you choose to draw - in this case, the text box.2. Move the pointer onto your form. The pointer becomes a cross hair, as shown in Figure 2.3.

    1. Figure 2.3 Drawing a text box with the Toolbox

    1.

    1. Place the cross hair where you want the upper-left corner of the control.2. Drag the cross hair until the control is the size you want. ( Dragging means holding the left mouse button down while

    you move an object with the mouse.)3. Release the mouse button.

    1. The control appears on the form.

    Another simple way to add a control to a form is to double-click the button for that control in the Toolbox. This creates adefault-size control located in the center of the form; then you can move the control to another location on the form.

  • 8/9/2019 Visual basic 5 Apostila

    22/641

    Resizing, Moving, and Locking Controls

    Notice that small rectangular boxes called sizing handles appear at the corners of the control; you’ll use these sizing handlesin the next step as you resize the control. You can also use the mouse, keyboard, and menu commands to move controls, lock and unlock control positions, and adjust their positions.

    To resize a control

    1. Select the control you intend to resize by clicking it with the mouse.

    1. Sizing handles appear on the control.

    1. Position the mouse pointer on a sizing handle, and drag it until the control is the size you choose.

    1. The corner handles resize controls horizontally and vertically, while the side handles resize in only one direction.

    1. Release the mouse button.

    1. or

    1. Use SHIFT with the arrow keys to resize the selected control.

    To move a control

    Use the mouse to drag the control to a new location on the form.

    1. or

    1. Use the Properties window to change the Top and Left properties.

    When a control is selected, you can use CTRL with the arrow keys to move the control one grid unit at a time. If the grid isturned off, the control moves one pixel at a time.

    To lock all control positions

    From the Format menu, choose Lock Controls.

    1. or

    1. Click the Lock Controls Toggle button on the Form Editor toolbar.

    This will lock all controls on the form in their current positions so that you don’t inadvertently move them once you havethem in the desired location. This will lock controls only on the selected form; controls on other forms are untouched. This isa toggle command, so you can also use it to unlock control positions.

    To adjust the position of locked controls

    You can "nudge" the control that has the focus by holding CTRL down and pressing the appropriate arrow key.

    1. or

    1. You can change the control’s Top and Left properties in the Property window.

    You now have the interface for the "Hello, world!" application, as shown in Figure 2.4.

    Figure 2.4 The interface for the "Hello, world!" application

  • 8/9/2019 Visual basic 5 Apostila

    23/641

    Setting Properties

    The next step is to set properties for the objects you’ve created. The Properties window (Figure 2.5) provides an easy way toset properties for all objects on a form. To open the Properties window, choose the Properties Window command from theView menu, click the Properties Window button on the toolbar, or use the context menu for the control.

    Figure 2.5 The Properties window

    The Properties window consists of the following elements:

    Object box - Displays the name of the object for which you can set properties. Click the arrow to the right of the objectbox to display the list of objects for the current form.Sort tabs - Choose between an alphabetic listing of properties or a hierarchical view divided by logical categories,such as those dealing with appearance, fonts, or position.Properties list - The left column displays all of the properties for the selected object. You can edit and view settings inthe right column.

    To set properties from the Properties window

    1. From the View menu, choose Properties, or click the Properties button on the toolbar.

    1. The Properties window displays the settings for the selected form or control.

    1. From the Properties list, select the name of a property.2. In the right column, type or select the new property setting.

    1. Enumerated properties have a predefined list of settings. You can display the list by clicking the down arrow at theright of the Settings box, or you can cycle through the list by double-clicking a list item.

  • 8/9/2019 Visual basic 5 Apostila

    24/641

    For the "Hello, world!" example, you’ll need to change three property settings. Use the default settings for all otherproperties.

    Object Property Setting

    Form Caption Hello, world!

    Text box Text (Empty)

    Command button Caption OK

    Setting the Icon Property

    All forms in Visual Basic have a generic, default icon that appears when you minimize that form. However, you willprobably change this icon to one that illustrates the use of the form or your application. To assign an icon to a form, set theIcon property for that form. You can use 32 x 32 pixel icons that were standard in 16-bit versions of Microsoft Windows andare also used in Windows 95 and Windows NT, as well as the 16 x 16 pixel icons used in Windows 95.

    Writing Code

    The Code Editor window is where you write Visual Basic code for your application. Code consists of language statements,constants, and declarations. Using the Code Editor window, you can quickly view and edit any of the code in yourapplication.

    To open the Code window

    Double-click the form or control for which you choose to write code.

    1. or

    1. From the Project Explorer window, select the name of a form or module, and choose the View Code button.

    Figure 2.6 shows the Code Editor window that appears when you double-click the Command button control, and the eventsfor that command.

    Figure 2.6 The Code Editor window

    You can choose to display all procedures in the same Code window, or display a single procedure at a time.

  • 8/9/2019 Visual basic 5 Apostila

    25/641

    To display all procedures in the same Code window

    1. From the Tools menu, select the Options dialog box.2. On the Editor tab in the Options dialog box, select the check box to the left of Default to Full Module View. The

    check box to the left of Procedure Separator adds or removes a separator line between procedures.

    1. or

    1. Click the Full Module View button in the lower left corner of the Code Editor window.

    To display one procedure at a time in the Code window

    1. From the Tools menu, select the Options dialog box.2. On the Editor tab in the Options dialog box, clear the check box to the left of Default to Full Module View.

    1. or

    1. Click the Procedure View button in the lower left corner of the Code Editor window.

    The Code window includes the following elements:

    Object list box - Displays the name of the selected object. Click the arrow to the right of the list box to display a list of all objects associated with the form.Procedure list box - Lists the procedures, or events, for an object. The box displays the name of the selected procedure- in this case, Click. Choose the arrow to the right of the box to display all the procedures for the object.

    Creating Event Procedures

    Code in a Visual Basic application is divided into smaller blocks called  procedures. An event procedure, such as those you’llcreate here, contains code that is executed when an event occurs (such as when a user clicks a button). An event procedurefor a control combines the control’s actual name (specified in the Name property), an underscore (_), and the event name. Forexample, if you want a command button named Command1 to invoke an event procedure when it is clicked, use theprocedure Command1_Click.

    To create an event procedure

    1. In the Object list box, select the name of an object in the active form. (The active form is the form that currently hasthe focus.)

    1. For this example, choose the command button, Command1.

    1. In the Procedure list box, select the name of an event for the selected object.

    1. Here, the Click procedure is already selected, because it’s the default procedure for a command button. Note that atemplate for the event procedure is now displayed in the Code window.

    1. Type the following code between the Sub and End Sub statements:

    Text1.Text = "Hello, world!" 

    1. The event procedure should look like this:

    Private Sub Command1_Click ()

      Text1.Text = "Hello, world!"

      End Sub

  • 8/9/2019 Visual basic 5 Apostila

    26/641

    You’ll note here that the code is simply changing the Text property of the control named Text1 to read "Hello, world!" Thesyntax for this example takes the form of object.property, where Text1 is the object and Text is the property. You can use thissyntax to change property settings for any form or control in response to events that occur while your application is running.

    For More Information For information on creating other types of procedures, see "Introduction to Procedures" in Chapter 5,"Programming Fundamentals."

    Running the Application

    To run the application, choose Start from the Run menu, or click the Start button on the toolbar, or press F5. Click thecommand button you’ve created on the form, and you’ll see "Hello, world!" displayed in the text box.

    The Firstapp Sample Application

    Visual Basic provides you with a wealth of tools beyond the ones used in this first application, so you’ll soon use many otherfeatures to manage and customize your applications. Reviewing sample applications can be an excellent way to learn moreabout Visual Basic. The following example illustrates how easy it can be to create a useful application in Visual Basic.

    The Firstapp application demonstrates how a data control and a grid control can be used to display a table of informationfrom a database. Visual Basic makes it easy to access database information from within your application. The data controlprovides the ability to navigate through the database recordset , synchronizing the display of records in the grid control withthe position in the recordset.

    The application consists of a data control, an Apex Data Bound Grid (DBGrid) control, a list box control, and two commandbuttons. The grid displays a table of information about programming books retrieved from the Biblio.mdb database. As theuser selects an item in the grid by clicking within the grid or by using the navigation buttons on the data control, the title of the selected book is displayed in the data control. The user can also add items to a "shopping list" in the list box control bydouble-clicking the current selection in the grid.

    To add items to the list box, you use the AddItem method. (A method  is a Visual Basic function that acts on a particularobject, in this case a ListBox object.) The syntax for specifying a method (object.method ) is similar to the syntax for setting a

    property (object.property). The AddItem method allows you to dynamically add items to the list box while the application isrunning. Conversely, the Clear method is used to remove all items from the list box.

    For More Information To learn more about methods, see "Understanding Properties, Methods, and Events" in Chapter 3,"Forms, Controls, and Menus."

    Creating a Project

    You begin creating this application by choosing New Project from the File menu, then selecting Standard EXE in the NewProject dialog box (when you first start Visual Basic, the New Project dialog box is presented). Visual Basic creates a new project  and displays a new form. To draw the interface, you use a data control, a DBGrid control, a list box control, and twocommand buttons. The DBGrid control isn’t in the default toolbox, so you’ll need to add it:

    To add a control to the toolbox

    1. Select Components from the context menu for the toolbox. (You can right-click within the toolbox window to displaythe context menu.)

    1. The Components dialog box will be displayed. 

    1. Find the Apex Data Grid (DBGrid) in the Controls list box and select the check box to its left.2. Click the OK button.

  • 8/9/2019 Visual basic 5 Apostila

    27/641

  • 8/9/2019 Visual basic 5 Apostila

    28/641

    The DatabaseName property of the data control must include the actual path to the database. By default, the Biblio.mdbdatabase is installed in the same directory as Visual Basic. When you select the DatabaseName property in the propertieswindow, you can click the button to the right of the property to display a standard FileOpen dialog box to browse for the file.Once the DatabaseName property has been set, the RecordSource property in the Properties window will contain a list of tables or recordsets for the selected database. Setting the DataSource property of the DBGrid control to Data1 automaticallylinks the grid to the data control.

    Writing Event Code

    All the code for the application is contained in the Command1_Click, Command2_Click, Data1_Reposition, andDBGrid1_DblClick event procedures. Double-click the form or control to display the Code window, and then type the codefor each event procedure.

    Add this code to the Command1_Click event procedure to clear the list box when the user clicks the button:

      Private Sub Command1_Click ()

      List1.Clear ’ Clears the list box.

      End Sub

    In the above statement, you are invoking the Clear method of the list box, List1. The Clear method deletes the contents of thelist box.

    Add this code to the Command2_Click event procedure to unload the form from memory and end the application:

      Private Sub Command2_Click ()

      Unload Form1

      End ’ Ends application.

      End Sub

    In the above procedure, the first statement invokes the Unload event for the form. If you needed to perform a function atshutdown, such as saving a file, you could place that code in the form’s Unload event procedure. The second statement callsthe End function, which ends the application.

    Add this code to the Data1_Reposition event procedure to update the caption each time a record is selected:

      Private Sub Data1_Reposition ()

      Data1.Caption = Data1.Recordset("Title")

      End Sub

    In the above statement, you are assigning the value on the right (the contents of the Title field in the Recordset of the datacontrol) to the property on the left (the Caption property of the data control object).

    Add this code to the DBGrid_DblClick event procedure to add an item to the list box when the user double-clicks a selectedrow:

      Private Sub DBGrid1_DblClick ()

      List1.AddItem Data1.Recordset("Title")

      End Sub

    In the above statement, you are invoking the AddItem method of the list box (List1). The text to be added to the list box iscontained in the argument  of the method, in this case, the value of the title field in the recordset of the data control. Passing avalue to an argument is similar to assigning a value to a property; unlike the assignment statement, the equal sign isn’trequired.

  • 8/9/2019 Visual basic 5 Apostila

    29/641

    Saving a Project

    You finish your work on the application by choosing Save Project from the File menu. Visual Basic will prompt youseparately to save the form and then the project. One possible name for the project is "Bookstore Shopping List." BothWindows 95 and Windows NT allow you to use file names up to 255 characters in length, and file names can include spaces.Older versions of Microsoft Windows limited you to file names of eight characters, with a three-character extension.

    Enhancing Your Application

    You have just completed your first Visual Basic application: one that performs a simple but useful function. You can use thisapplication as a basis for adding similar functionality in your own applications, substituting your own data instead of Biblio.mdb. Of course, to make this application truly useful, you might want to add functionality to save or print the contentsof the list box, to add additional information such as price and availability, and even to gather credit card information andtransmit an order across the Internet. As you continue on through the rest of the Programmer’s Guide, you will find examplesof doing all that and a lot more.

  • 8/9/2019 Visual basic 5 Apostila

    30/641

    Chapter 3.

    Forms, Controls, and Menus

    The first step to creating an application with Visual Basic is to create the interface, the visual part of the application withwhich the user will interact. Forms and controls are the basic building blocks used to create the interface; they are the objectsthat you will work with to build your application.

    Forms are objects that expose properties which define their appearance, methods which define their behavior, and eventswhich define their interaction with the user. By setting the properties of the form and writing Visual Basic code to respond toits events, you customize the object to meet the requirements of your application.

    Controls are objects that are contained within form objects. Each type of control has its own set of properties, methods andevents that make it suitable for a particular purpose. Some of the controls you can use in your applications are best suited forentering or displaying text. Other controls let you access other applications and process data as if the remote application waspart of your code.

    This chapter introduces the basic concepts of working with forms and controls and their associated properties, methods, andevents. Many of the standard controls are discussed, as well as form-specific items such as menus and dialog boxes.

    Contents

    Understanding Properties, Methods and EventsDesigning a FormClicking Buttons to Perform ActionsControls for Displaying and Entering TextControls That Present Choices to UsersControls That Display Pictures and GraphicsAdditional ControlsUnderstanding Focus

    Setting the Tab OrderMenu BasicsPrompting the User with Dialog Boxes

    Sample Application: Controls.vbp

    The code examples in this chapter are taken from the Controls.vbp sample application. If you installed the sampleapplications, you will find them in the \Controls subdirectory of the Visual Basic samples directory(\Vb\Samples\Pguide\Controls).

    Understanding Properties, Methods and Events

    Visual Basic forms and controls are objects which expose their own properties, methods and events. Properties can bethought of as an object’s attributes, methods as its actions, and events as its responses.

    An everyday object like a child’s helium balloon also has properties, methods and events. A balloon’s properties includevisible attributes such as its height, diameter and color. Other properties describe its state (inflated or not inflated), orattributes that aren’t visible such as its age. By definition, all balloons have these properties; the settings of these propertiesmay differ from one balloon to another.

    A balloon also has inherent methods or actions that it might perform. It has an inflate method (the action of filling it withhelium), a deflate method (expelling its contents) and a rise method (if you were to let go of it). Again, all balloons are

  • 8/9/2019 Visual basic 5 Apostila

    31/641

    capable of these methods.

    Balloons also have predefined responses to certain external events. For instance, a balloon would respond to the event of being punctured by deflating itself, or to the event of being released by rising into the air.

    Figure 3.1 Objects have properties, respond to events, and perform methods

    If you were able to program a balloon, the Visual Basic code might look like the following. To set the balloon’s properties:

      Balloon.Color = Red

      Balloon.Diameter = 10

      Balloon.Inflated = True

    Note the syntax of the code - the object (Balloon) followed by the property (.Color) followed by the assignment of the value(Red). You could change the color of the balloon from code by repeating this statement and substituting a different value.Properties can also be set in the Properties window while you are designing your application.

    A balloon’s methods are invoked like this:

      Balloon.Inflate

      Balloon.Deflate

      Balloon.Rise 5

    The syntax is similar to the property - the object (a noun) followed by the method (a verb). In the third example, there is anadditional item, called an argument , which denotes the distance to rise. Some methods will have one or more arguments tofurther describe the action to be performed.

    The balloon might respond to an event as follows:

      Sub Balloon_Puncture()

      Balloon.Deflate

      Balloon.MakeNoise "Bang"

      Balloon.Inflated = False

      Balloon.Diameter = 1

      End Sub

    In this case, the code describes the balloon’s behavior when a puncture event occurs: invoke the Deflate method, then invokethe MakeNoise method with an argument of "Bang" (the type of noise to make). Since the balloon is no longer inflated, theInflated property is set to False and the Diameter property is set to a new value.

    While you can’t actually program a balloon, you can program a Visual Basic form or control. As the programmer, you are incontrol. You decide which properties should be changed, methods invoked or events responded to in order to achieve thedesired appearance and behavior.

  • 8/9/2019 Visual basic 5 Apostila

    32/641

    Designing a Form

    Form objects are the basic building blocks of a Visual Basic application, the actual windows with which a user interacts whenthey run the application. Forms have their own properties, events, and methods with which you can control their appearance

    and behavior.

    Figure 3.2 Forms and controls have their own properties, events, and methods

    The first step in designing a form is to set its properties. You can set a form’s properties at design time in the Propertieswindow, or at run time by writing code.

    Note You work with forms and controls, set their properties, and write code for their events at design time, which is any timeyou’re building an application in the Visual Basic environment. Run time is any time you are actually running the applicationand interacting with the application as the user would.

    Setting Form Properties

    Many of a form’s properties affect its physical appearance. The Caption property determines the text that is shown in theform’s title bar; the Icon property sets the icon that is displayed when a form is minimized. The MaxButton and MinButtonproperties determine whether the form can be maximized or minimized. By changing the BorderStyle property, you can

    control the resizing behavior of the form.

    Height and Width properties determine the initial size of a form; Left and Top properties determine the form’s location inrelation to the upper left-hand corner of the screen. The WindowState property can be set to start the form in a maximized,minimized, or normal state.

    The Name property sets the name by which you will refer to the form in code. By default, when a form is first added to aproject, its name is set to Form1, Form2, and so forth. It’s a good idea to set the Name property to something moremeaningful, such as "frmEntry" for an order entry form.

    The best way to familiarize yourself with the many form properties is to experiment. Change some of the properties of a formin the Properties window (Figure 3.3), then run the application to see their effect. You can learn more about each property byselecting it and pressing F1 to view the context-sensitive Help.

    Figure 3.3 The Properties window

  • 8/9/2019 Visual basic 5 Apostila

    33/641

    Form Events and Methods

    As objects, forms can perform methods and respond to events.

    The Resize event of a form is triggered whenever a form is resized, either by user interaction or through code. This allowsyou to perform actions such as moving or resizing controls on a form when its dimensions have changed.

    The Activate event occurs whenever a form becomes the active form; the Deactivate event occurs when another form or

    application becomes active. These events are convenient for initializing or finalizing the form’s behavior. For example, in theActivate event you might write code to highlight the text in a particular text box; in the Deactivate event you might savechanges to a file or database.

    To make a form visible, you would invoke the Show method:

    Form2.Show

    Invoking the Show method has the same effect as setting a form’s Visible property to True.

    Many of a form’s methods involve text or graphics. The Print, Line, Circle, and Refresh methods are useful for printing ordrawing directly onto a form’s surface. These methods and more are discussed in Chapter 12, "Working with Text andGraphics."

    For More Information For additional information on forms, see "More About Forms" in Chapter 6, "Creating a UserInterface."

    Clicking Buttons to Perform Actions

    The easiest way to allow the user to interact with an application is to provide a button to click. You can use the commandbutton control provided by Visual Basic, or you can create your own "button" using an image control containing a graphic,such as an icon.

    Using Command Buttons

    Most Visual Basic applications have command buttons that allow the user to simply click them to perform actions. When theuser chooses the button, it not only carries out the appropriate action, it also looks as if it’s being pushed in and released.Whenever the user clicks a button, the Click event procedure is invoked. You place code in the Click event procedure toperform any action you choose.

    There are many ways to choose a command button at run time:

    Use a mouse to click the button.Move the focus to the button by pressing the TAB key, and then choose the button by pressing the SPACEBAR or ENTER.(See "Understanding Focus" later in this chapter.)Press an access key (ALT+ the underlined letter) for a command button.

  • 8/9/2019 Visual basic 5 Apostila

    34/641

    Set the command button’s Value property to True in code:

    1. cmdClose.Value = True 

    Invoke the command button’s Click event in code:

    1. cmdClose_Click

    If the command button is the default  command button for the form, pressing ENTER chooses the button, even if youchange the focus to a different control other than a command button. At design time, you specify a default commandbutton by setting that button’s Default property to True.If the command button is the default Cancel button for the form, then pressing ESC chooses the button, even if youchange the focus to another control. At design time, you specify a default Cancel button by setting that button’sCancel property to True.

    All these actions cause Visual Basic to invoke the Click event procedure.

    The Test Buttons Application

    You use the Caption property to display text on the button to tell the user what the button does. In Figure 3.4, the TestButtons example from the Controls sample application contains a command button with its Caption property set to "ChangeSignal." (For a working version of this example, see Button.frm in the Controls.vbp sample application.)

    Notice that ’S’ is the access key for this button, denoted by an underline. Inserting an ampersand (&) in the text of theCaption property makes the character following it the access key for that button (for example, Change &Signal).

    Figure 3.4 Command button with a caption

    When a user clicks the command button, the code in the command button’s Click event procedure is executed. In theexample, a different traffic light icon is displayed each time the button is clicked.

    For More Information For information on additional properties of the command button, see Chapter 7, "Using VisualBasic’s Standard Controls."

    Controls for Displaying and Entering Text

    Label and text box controls are used to display or enter text. Use labels when you want your application to display text on aform, and text boxes when you want to allow the user to enter text. Labels contain text that can only be read, while text boxescontain text that can be edited.

  • 8/9/2019 Visual basic 5 Apostila

    35/641

    To provide this feature Use this control

    Text that can be edited by the user,for example an order entry field ora password box

    Text box

    Text that is displayed only, for

    example to identify a field on aform or display instructions to theuser

    Label

     

    Using Labels to Display Text

    A label control displays text that the user cannot directly change. You can use labels to identify controls, such as text boxesand scroll bars, that do not have their own Caption property. The actual text displayed in a label is controlled by the Captionproperty, which can be set at design time in the Properties window or at run time by assigning it in code.

    By default, the caption is the only visible part of the label control. However, if you set the BorderStyle property to 1 (whichyou can do at design time), the label appears with a border - giving it a look similar to a text box. You can also change theappearance of the label by setting the BackColor, BackStyle, ForeColor, and Font properties.

    Sizing a Label to Fit Its Contents

    Single-line label captions can be specified at design time in the Properties window. But what if you want to enter a longercaption, or a caption that will change at run time? Labels have two properties that help you size the controls to fit larger orsmaller captions: AutoSize and WordWrap.

    The AutoSize property determines if a control should be automatically resized to fit its contents. If set to True, the labelgrows horizontally to fit its contents, as shown in Figure 3.5.

    Figure 3.5 AutoSize example

    The WordWrap property causes the label to grow vertically to fit its contents, while retaining the same width, as shown inFigure 3.6. For a working version of this example, see Wordwrap.frm in the Controls.vbp sample application.

    Figure 3.6 WordWrap example

  • 8/9/2019 Visual basic 5 Apostila

    36/641

    Note If you run the AutoSize example from Controls.vbp, you’ll notice that for the WordWrap example to actually work,both check boxes must be selected. This is because, for the label’s WordWrap property to take effect, AutoSize must be set toTrue. The width of the label is increased only if the width of a single word exceeds the current width of the control.

    For More Information For additional information on the label control’s properties, see Chapter 7, "Using Visual Basic’sStandard Controls."

    Working with Text Boxes

    Text boxes are versatile controls that can be used to get input from the user or to display text. Text boxes should not be usedto display text that you don’t want the user to change, unless you’ve set the Locked property to True.

    The actual text displayed in a text box is controlled by the Text property. It can be set in three different ways: at design timein the Property window, at run time by setting it in code, or by input from the user at run time. The current contents of a textbox can be retrieved at run time by reading the Text property.

    Multiple-Line Text Boxes and Word Wrap

    By default, a text box displays a single line of text and does not display scroll bars. If the text is longer than the availablespace, only part of the text will be visible. The look and behavior of a text box can be changed by setting two properties,MultiLine and ScrollBars, which are available only at design time.

    Note The ScrollBars property should not be confused with scroll bar controls, which are not attached to text boxes and havetheir own set of properties.

    Setting MultiLine to True enables a text box to accept or display multiple lines of text at run time. A multiple-line text boxautomatically manages word wrap as long as there is no horizontal scroll bar. The ScrollBars property is set to 0-None bydefault. Automatic word wrap saves the user the trouble of inserting line breaks at the end of lines. When a line of text islonger than what can be displayed on a line, the text box wraps the text to the next line.

    Line breaks cannot be entered in the Properties window at design time. Within a procedure, you create a line break byinserting a carriage return followed by a linefeed (ANSI characters 13 and 10). You can also use the constant vbCrLf to inserta carriage return/linefeed combination. For example, the following event procedure puts two lines of text into a multiple-linetext box (Text1) when the form is loaded:

      Sub Form_Load ()

      Text1.Text = "Here are two lines" _ 

      & vbCrLf & "in a text box"

      End Sub

  • 8/9/2019 Visual basic 5 Apostila

    37/641

    Working with Text in a Text Box

    You can control the insertion point and selection behavior in a text box with the SelStart, SelLength and SelText properties.These properties are only available at run time.

    When a text box first receives the focus, the default insertion point or cursor position within the text box is to the left of any

    existing text. It can be moved by the user from the keyboard or with the mouse. If the text box loses and then regains thefocus, the insertion point will be wherever the user last placed it.

    In some cases, this behavior can be disconcerting to the user. In a word processing application, the user might expect newcharacters to appear after any existing text. In a data entry application, the user might expect their typing to replace anyexisting entry. The SelStart and SelLength properties allow you to modify the behavior to suit your purpose.

    The SelStart property is a number that indicates the insertion point within the string of text, with 0 being the left-mostposition. If the SelStart property is set to a value equal to or greater than the number of characters in the text box, theinsertion point will be placed after the last character, as shown in Figure 3.7. For a working version of this example, seeText.frm in the Controls.vbp sample application.

    Figure 3.7 Insertion point example

    The SelLength property is a numeric value that sets the width of the insertion point. Setting the SelLength to a numbergreater than 0 causes that number of characters to be selected and highlighted, starting from the current insertion point. Figure3.8 shows the selection behavior.

    Figure 3.8 Selection example

    If the user starts typing while a block of text is selected, the selected text will be replaced. In some cases, you might want toreplace a text selection with new text by using a paste command. The SelText property is a string of text that you can assignat run time to replace the current selection. If no text is selected, SelText will insert its text at the current insertion point.

  • 8/9/2019 Visual basic 5 Apostila

    38/641

    For More Information For additional information on the text box control’s properties, see Chapter 7, "Using Visual Basic’sStandard Controls."

    Controls That Present Choices to Users

    Most applications need to present choices to their users, ranging from a simple yes/no option to selecting from a listcontaining hundreds of possibilities. Visual Basic includes several standard controls that are useful for presenting choices.The following table summarizes these controls and their appropriate uses.

    To provide this feature Use this control

    A small set of choices from which auser can choose one or moreoptions.

    Check boxes

    A small set of options from which auser can choose just one.

    Option buttons (use frames if additional groups are needed)

    A scrollable list of choices from

    which the user can choose.

    List box

    A scrollable list of choices alongwith a text edit field. The user caneither choose from the list or type achoice in the edit field.

    Combo box

     

    Selecting Individual Options with Check Boxes

    A check box indicates whether a particular condition is on or off. You use check boxes in an application to give userstrue/false or yes/no options. Because check boxes work independently of each other, a user can select any number of check boxes at the same time. For example in Figure 3.9, Bold and Italic can both be checked.

    Figure 3.9 Check boxes

    The Check Box Application

    The Check Box example uses a check box to determine whether the text is displayed in regular or italic font. For a workingversion of this example, see Check.frm in the Controls.vbp sample application.

    The application has a text box, a label, a command button, and two check boxes, as shown in Figure 3.10.

    Figure 3.10 Check box example

  • 8/9/2019 Visual basic 5 Apostila

    39/641

  • 8/9/2019 Visual basic 5 Apostila

    40/641

    Option buttons present a set of two or more choices to the user. Unlike check boxes, however, option buttons should alwayswork as part of a group; selecting one option button immediately clears all the other buttons in the group. Defining an optionbutton group tells the user, "Here is a set of choices from which you can choose one and only one."

    For example, in the option button group shown in Figure 3.11, the user can select one of three option buttons.

    Figure 3.11 Selecting an option button

    Creating Option Button Groups

    All of the option buttons placed directly on a form (that is, not in a frame or picture box) constitute one group. If you want tocreate additional option button groups, you must place some of them inside frames or picture boxes.

    All the option buttons inside any given frame constitute a separate group, as do all the option buttons inside a picture box.

    When you create a separate group this way, always draw the frame or picture box first, and then draw the option buttons ontop of it. Figure 3.12 shows a form with two option button groups.

    Figure 3.12 Option button groups

    A user can select only one option button in the group when you draw option buttons in a frame.

    To group controls in a frame

    1. Select the frame control from the toolbox and draw the frame on the form.2. Select the option button control from the toolbox and draw the control within the frame.3. Repeat step 2 for each additional option button you wish to add to the frame.

    Drawing the frame first and then drawing each control on the frame allows you to move the frame and controls together. If you try to move existing controls onto a frame, the controls will not move with the frame.

    Note If you have existing controls that you want to group in a frame, you can select all the controls and cut and paste theminto a frame or picture control.

    Containers for Controls

    While controls are independent objects, a certain  parent and child relationship exists between forms and controls. Figure

  • 8/9/2019 Visual basic 5 Apostila

    41/641

    3.12 demonstrates how option buttons can be contained within a form or within a frame control.

    To understand the concept of containers, you need to understand that all controls are children of the form on which they aredrawn. In fact, most controls support the read-only Parent property, which returns the form on which a control is located.Being a child affects the placement of a control on the parent form. The Left and Top properties of a control are relative tothe parent form, and controls cannot be moved outside the boundaries of the parent. Moving a container moves the controlsas well, and the control’s position relative to the container’s Left and Top properties does not change because the control

    moves with the container.

    Selecting or Disabling Option Buttons

    An option button can be selected by:

    Clicking it at run time with the mouse.Tabbing to the option button group and then using the arrow keys to select an option button within the group.Assigning its Value property to True in code:

    1. optChoice.Value = True 

    Using a shortcut key specified in the caption of a label.

    To make a button the default in an option button group, set its Value property to True at design time. It remains selected untila user selects a different option button or code changes it.

    To disable an option button, set its Enabled property to False. When the program is run it will appear dimmed, meaning thatit is unavailable.

    The Options Application

    The form shown in Figure 3.13 uses option buttons to determine the processor type and operating system for a fictionalcomputer. When the user selects a option button in either group, the caption of the label is changed to reflect the currentchoices. For a working version of this example, see Options.frm in the Controls.vbp sample application.

    Figure 3.13 Option button example

    The following table lists the property settings for the objects in the application.

  • 8/9/2019 Visual basic 5 Apostila

    42/641

    Object Property Setting

    Label NameCaption

    lblDisplay(Empty)

    Command button NameCaption

    cmdClose&Close

    First option button NameCaption

    opt486&486

    Second optionbutton

    NameCaption

    Value

    opt586&Pentium

    True

    Third option button NameCaption

    opt686P&entium Pro

    Frame NameCaption

    fraSystem&Operating System

    Fourth optionbutton

    NameCaption

    optWin95Windows 95

    Fifth option button NameCaption

    Value

    optWinNTWindows NT

    True

    Events in the Options Application

    The Options application responds to events as follows:

    The Click events for the first three option buttons assign a corresponding description to a form-level string variable,strComputer.The Click events for the last two option buttons assign a corresponding description to a second form-level variable,strSystem.

    The key to this approach is the use of these two form-level variables, strComputer and strSystem. These variables containdifferent string values, depending on which option buttons were last selected.

    Each time a new option button is selected, the code in its Click event updates the appropriate variable:

      Private Sub opt586_Click()

      strComputer = "Pentium"

      Call DisplayCaption

      End Sub

    It then calls a sub procedure, called DisplayCaption, that concatenates the two variables and updates the label’s Captionproperty:

      Sub DisplayCaption()

      lblDisplay.Caption = "You selected a " & _ 

      strComputer & " running " & strSystem

      End Sub

  • 8/9/2019 Visual basic 5 Apostila

    43/641

    A sub procedure is used because the procedure of updating the Caption property is essentially the same for all five optionbuttons, only the value of the variables change from one instance to the next. This saves you from having to repeat the samecode in each of the Click events.

    For More Information Variables and sub procedures are discussed in detail in Chapter 5, "Programming Fundamentals."

    Using List Boxes and Combo Boxes

    List boxes and combo boxes present a list of choices to the user. By default, the choices are displayed vertically in a singlecolumn, although you can set up multiple columns as well. If the number of items exceeds what can be displayed in thecombo box or list box, scroll bars automatically appear on the control. The user can then scroll up and down or left to rightthrough the list. Figure 3.14 shows a single-column list box.

    Figure 3.14 Single-column list box

    A combo box control combines the features of a text box and a list box. This control allows the user to select either by typingtext into the combo box or by selecting an item from its list. Figure 3.15 shows a combo box.

    Figure 3.15 Combo box

    In contrast to some other controls that contain a single value; for example the label’s Caption property or the text box’s Textproperty, list boxes and combo boxes contain multiple values or a collection of values. They have built-in methods foradding, removing and retrieving values from their collections at run time. To add several items to a list box named List1, thecode would look like this:

      List1.AddItem "Paris"

      List1.AddItem "New York"

      List1.AddItem "San Francisco"

    List boxes and combo boxes are an effective way to present a large number of choices to the user in a limited amount of space.

    For More Information For additional information on the list box and combo box controls, see Chapter 7, "Using Visual

    Basic’s Standard Controls."

    Using Scroll Bars as Input Devices

    Although scroll bars are often tied to text boxes or windows, you’ll sometimes see them used as input devices. Because thesecontrols can indicate the current position on a scale, scroll bar controls can be used individually to control program input - forexample, to control the sound volume or to adjust the colors in a picture. The HScrollBar (horizontal) and VScrollBar

  • 8/9/2019 Visual basic 5 Apostila

    44/641

    (vertical) controls operate independently from other controls and have their own set of events, properties, and methods. Scrollbar controls are not the same as the built-in scroll bars that are attached to text boxes, list boxes, combo boxes, or MDI forms(text boxes and MDI forms have a ScrollBars property to add or remove scroll bars that are attached to the control).

    Windows interface guidelines now suggest using slider controls as input devices instead of scroll bars. Examples of slidercontrols can be seen in the Windows 95 control panel. A Windows 95 style slider control is included in the Professional andEnterprise editions of Visual Basic.

    For More Information For additional information on scroll bar controls, see Chapter 7, "Using Visual Basic’s StandardControls."

    Controls That Display Pictures and Graphics

    Because Windows is a graphical user interface, it’s important to have a way to display graphical images in your application’sinterface. Visual Basic includes four controls that make it easy to work with graphics: the picture box control, the imagecontrol, the shape control, and the line control.

    The image, shape and line controls are sometimes referred to as "lightweight" graphical controls. They require less systemresources and consequently display somewhat faster than the picture box control; they contain a subset of the properties,

    methods and events available in the picture box. Each is best suited for a particular purpose.

    To provide this feature Use this control

    A container for other controls. Picture box

    Printing or graphics methods. Picture box

    Displaying a picture. Image control or picture box

    Displaying a simple graphicalelement

    Shape or line control

     

    Working With the Picture Box Control

    The primary use for the picture box control is to display a picture to the user. The actual picture that is displayed isdetermined by the Picture property. The Picture property contains the file name (and optional path) for the picture file thatyou wish to display.

    Note Form objects also have a Picture property that can be set to display a picture directly on the form’s background.

    To display or replace a picture at run time, you can use the LoadPicture function to set the Picture property. You supply the

    name (and optional path) for the picture and the LoadPicture function handles the details of loading and displaying it:

    picMain.Picture = LoadPicture("VANGOGH.BMP")

    The picture box control has an AutoSize property that, when set to True, causes the picture box to resize automatically tomatch the dimensions of its contents. Take extra care in designing your form if you plan on using a picture box with theAutoSize enabled. The picture will resize without regard to other controls on the form, possibly causing unexpected results,such as covering up other controls. It’s a good idea to test this by loading each of the pictures at design time.

    Using the Picture Box as a Container

  • 8/9/2019 Visual basic 5 Apostila

    45/641

    The picture box control can also be used as a container for other controls. Like the frame control, you can draw other controlson top of the picture box. The contained controls move with the picture box and their Top and Left properties will be relativeto the picture box rather than the form.

    A common use for the picture box container is as a toolbar or status bar. You can place image controls on it to act as buttons,or add labels to display status messages. By setting the Align property to Top, Bottom, Left, or Right, the picture box will

    "stick" to the edge of the form. Figure 3.16 shows a picture box with its Align property set to Bottom. It contains two labelcontrols which could be used to display status messages.

    Figure 3.16 Picture box used as a status bar

    Other Uses for the Picture Box

    The picture box control has several methods that make