infor-Contents at a GlanceI Getting Started with Visual Basic 1 Starting Out with Visual Basic 11 2 Creating Your First Program 17 3 Visual Basic Building Blocks 39 4 Using Visual Basic’
Trang 1iContents
Trang 3Brian Siler and Jeff Spotts
Trang 4Special Edition Using Visual Basic® 6
Copyright© 1998 by Que
All rights reserved No part of this book shall be reproduced, stored
in a retrieval system, or transmitted by any means, electronic, chanical, photocopying, recording, or otherwise, without writtenpermission from the publisher No patent liability is assumed withrespect to the use of the information contained herein Althoughevery precaution has been taken in the preparation of this book, thepublisher and author assume no responsibility for errors or omis-sions Neither is any liability assumed for damages resulting fromthe use of the information contained herein
me-International Standard Book Number: 0-7897-1542-2Library of Congress Catalog Card Number: 98-84617Printed in the United States of America
First Printing: September 1998
00 99 98 4 3 2 1
Trademarks
All terms mentioned in this book that are known to be trademarks
or service marks have been appropriately capitalized Que cannotattest to the accuracy of this information Use of a term in this bookshould not be regarded as affecting the validity of any trademark orservice mark
Windows is a registered trademark of Microsoft Corporation
Visual Basic is a registered trademark of Microsoft Corporation
Warning and Disclaimer
Every effort has been made to make this book as complete and asaccurate as possible, but no warranty or fitness is implied Theinformation provided is on an “as is” basis The authors and thepublisher shall have neither liability or responsibility to any person
or entity with respect to any loss or damages arising from the mation contained in this book
Trang 5infor-Contents at a Glance
I Getting Started with Visual Basic
1 Starting Out with Visual Basic 11
2 Creating Your First Program 17
3 Visual Basic Building Blocks 39
4 Using Visual Basic’s Default Controls 59
II Programming with Visual Basic
5 Responding to the User with Event Procedures 95
6 Giving More Control to the User: Menus and Toolbars 107
7 Using Dialog Boxes to Get Information 139
8 Using Variables to Store Information 159
9 Visual Basic Programming Fundamentals 173
10 Controlling the Flow of Your Program Code 203
11 Managing Your Project: Sub Procedures, Functions, and Multiple Forms 223
III Visual Basic Program Components
12 Microsoft Common Controls 245
13 Working with Control Arrays 289
14 Creating ActiveX Controls 305
15 Extending ActiveX Controls 341
16 Classes: Resusable Components 359
IV Visual Basic Interfaces
17 Multiple Document Interface Applications 381
18 Proper Interface Design 409
19 Using Visual Design Elements 425
V Advanced Programming Topics
20 Accessing the Windows API 449
21 Working with Files 469
22 Using OLE to Control Other Applications 489
23 Master’s Toolbox 501
Trang 6VI Visual Basic and Databases
24 Database Basics 527
25 The Data Control and Data-Bound Controls 545
26 Using Data Access Objects (DAO) 565
27 Using Remote Data Objects (RDO) 595
28 Using ActiveX Data Objects (ADO) 611
A Introduction to the Development Environment 759
B Packaging Your Applications 775
C SQL Summary 793
Index 829
Trang 7Source Code and Programs Used in ThisBook 6
Conventions and Special Elements Used inThis Book 6
I Getting Started with Visual Basic 9
1 Starting Out with Visual Basic 11
What Is a Computer Program? 12Computer Programs and ProgrammingLanguages 13
Visual Basic Is a Smart Language 14The Importance of Designing YourProgram 14
How Design Fits into the ProgrammingProcess 15
Program Design in a Nutshell 15From Here… 16
2 Creating Your First Program 17
Creating Your Program’s User face 18
Inter-Getting Started 18Saving Your Work 20
Getting Information From the User 23Adding a TextBox Control 23Labeling Your Program’s Controls 28Adding a Command Button 29Changing a Form’s Properties 30Saving Your Work—Again… 31Coding Your Program’s Actions 31Responding to Events 31Specifying Event Procedures 33Writing Program Code 34Running Your Program 36From Here… 38
3 Visual Basic Building Blocks 39
Forms 40Parts of a Form 40What Do Forms Do? 41Using Controls 41What Are Controls? 41Control Functions 42Exploring Properties 42Property Basics 43Common Properties 44Using Properties to Control an Object’sSize 44
Using Properties to Adjust an Object’sPosition 44
Changing Properties at Runtime 45Using Properties to Control User Inter-action 48
Referencing Forms and Controls fromYour Code 49
A First Look at Methods and Events 50Taking Action with Methods 50Responding to Actions with Events 51How Properties and Methods Are Re-lated 51
Form Properties Revisited 52Displaying a Form 55From Here… 57
Trang 84 Using Visual Basic’s Default
Controls 59
Introduction to the Intrinsic Controls 60
Working with Text 62
Displaying Text with a Label trol 63
Con-Entering Text with a Text Box 65Controls for Making Choices 66
The Command Button 67Check Boxes 68
Option Buttons 68The List Box 70The Combo Box 75Special-Purpose Controls 78
Scrollbars 78The Timer Control 81Frames 83
Working with Multiple Controls at
Designtime 85
Selecting Multiple Controls 86Using the Properties Window 87Using the Form Editor Toolbar 87Using the Format Menu 89Multiple Controls in a Frame 90Working with the Controls Collection 90
Changing All Controls 90Changing Selected Controls 91From Here… 91
II Programming with Visual
Basic 93
5 Responding to the User with Event
Procedures 95
Introducing Events 96
Handling Events in Your Programs 97
Determining When an Event Has curred 97
Oc-Types of Events 98Writing Event Procedures 100
Calling an Event Procedure fromCode 101
Understanding Event Sequences 102Multiple Events for Each Action 102Determining the Order of Events 103From Here… 106
6 Giving More Control to the User: Menus and Toolbars 107
Creating a Menu Bar 108Common Menus 109Setting Up the Main Items 110Multiple-Level Menus 112Grouping Menu Items 114Modifying the Menu 115Adding Access Keys and Shortcut Keysfor Quick Access 116
Writing Code for the Menu Items 119Optional Settings 119
Creating Pop-Up Menus 122Creating the Menu to Be Dis-played 123
Activating a Pop-Up Menu 124Using Toolbars in Visual Basic 124Toolbar Basics 125
Getting the Images for YourToolbar 126
Creating a Standard Toolbar 127Creating the Toolbar’s Buttons 129Starting a Toolbar Example 131Enabling the Buttons with Code 132Creating a Toolbar with Code 133Allowing the User to Customize theToolbar 135
Using the CoolBar Control 136From Here… 137
7 Using Dialog Boxes to Get Information 139
Keeping the User Informed 140Understanding the Message Box 140Displaying a Message 141
Trang 9Returning a Value from the MsgBox
Function 143
Demonstrating the MsgBox
Func-tion 146Getting Information from the User 146
Setting Up the InputBox Function 146
Values Returned by InputBox 147Using Built-In Dialog Boxes 148General Usage of the CommonDialogControl 148
Testing the CommonDialog trol 149
Con-The File Dialog Boxes 150The Font Dialog Box 152The Color Dialog Box 154The Print Dialog Box 155The Help Dialog Box 157Creating Your Own Dialog Boxes 157Creating a Custom Dialog Box 157Using Form Templates for Other DialogBoxes 157
From Here… 158
8 Using Variables and Constants to Store Information 159
Introduction to Variables 160Naming Variables 160Types of Variables 161Variable Declarations 163Explicit Declaration 163Implicit Declaration 164Fixed-Length Strings 165Variable Arrays 166
Determining Where a Variable Can BeUsed 166
Creating Variables That Are AvailableEverywhere 167
Keeping a Variable Local 168Using Static Variables 168
Using the Option Explicit Statement 169
What’s Different About Constants 171How to Use Constants 171Constants That Visual Basic Sup-plies 171
Creating Your Own Constants 172From Here… 172
9 Visual Basic Programming Fundamentals 173
Writing Statements 174Using Assignment Statements 175Using Math Operations 176Addition and Subtraction 177Multiplication and Division 178Exponentiation 181
Operator Precedence 181Working with Strings 182String Concatenation 183Determining the Length of theString 185
Changing the Case of a String 185Searching a String 187
Extracting Pieces of a String 189Getting Rid of Spaces 191Replacing Characters in a String 191Working with Specific Characters 193Strings and Numbers 194
Formatting Results 195Specific Formatting Functions 195
Using the Format Function 197Manipulating Date Values 200From Here… 202
10 Controlling the Flow of Your Program Code 203
Making Decisions in Your Program 204
Using the If Statement 204
Working with the False Condition 205Working with Multiple If State-ments 206
Using Select Case 207
Trang 10Working with Loops 209
For Loops 210
Do Loops 211Enumeration Loops 214Debugging Your Programs 214
Stepping Through Your Code 216Working in the Immediate Win-dow 217
Tracking Variable Values 218Error Trapping 219
Using the On Error Statement 219Labeling Code Lines 219
Controlling Program Flow After
an Error 220Determining the Type of Error 221From Here… 222
11 Managing Your Project: Sub
Procedures, Functions, and Multiple
Forms 223
Using Procedures and Functions 224
Working with Procedures 224Working with Functions 231Determining the Scope of Proceduresand Functions 232
Reusing Functions and dures 233
Proce-Working with Multiple Forms 235
Adding New Forms to Your gram 235
Pro-Adding Code Modules to a Project 236Accessing the Forms and Modules of aProject 236
Managing Components in Your
Project 237
Managing Program References 238Controlling Your Controls 238Adding Forms, Modules, and Classes
to the Project 238Removing Pieces 241Controlling How Your Program Starts 241
Setting the Startup Form 241
Using Sub Main 241From Here… 242
III Visual Basic Program Components 243
12 Microsoft Common Controls 245
Introduction to the Common Controls 246The ImageList: A Fundamental CommonControl 248
Setting Up an ImageList atDesigntime 248
Setting Up an ImageList withCode 249
Organizing Your Data 250Using the ListView Control 251Using the TreeView Control 258Using the TabStrip Control 261Accepting User Input 266
Using an ImageCombo Control 266The UpDown Control 269
Working with Dates 271Sliding into Numbers 275Reporting Status and Progress 278Adding a Status Bar to Your Pro-gram 279
Progress Bar 284Adding Video with the Animation Con-trol 285
From Here… 287
13 Working with Control Arrays 289
Introducing Control Arrays 290Control Array Elements 290Understanding the Advantages of Con-trol Arrays 290
Creating a Control Array 291Adding Control Arrays to a Form 291Writing Code for a Control Array 294Removing Elements from a Control Ar-ray 296
Working with Control Arrays 296Using a Control Array in Your Pro-grams 296
Trang 11Parallel Arrays 297Creating a Menu Item Array 298Loading and Unloading Controls atRuntime 299
Creating the First Element of a ControlArray 299
Adding Controls at Runtime 300Removing Controls at Runtime 301From Here… 303
14 Creating ActiveX Controls 305
ActiveX Basics 306Steps Involved in Building ActiveX Con-trols 306
Development Strategies 307Creating an ActiveX Control 307Starting the Address ControlProject 307
Adding Resize Code to the Control 309Adding a New Property to Your Con-trol 310
Testing the ActiveX Control 311Testing with a Project Group 311Testing with Internet Explorer 313Compiling Your Control 314
Creating the OCX File 315Testing the Compiled Control 315Distributing the Control to AnotherMachine 315
Enhancing an ActiveX Control 317Setting Up the Base Control 318Enhancing the Base Control 319Testing the Limited Character TextBox 322
Choosing a Toolbox Icon 323Using the ActiveX Control InterfaceWizard 323
Adding the Wizard to Visual Basic 323Selecting and Creating Properties 324Mapping Properties 326
Finishing the Code 327
Using the Property Pages Wizard 330Creating the Pages 330
Adding Properties to the Pages 331Using the Property Pages in your Appli-cations 332
Creating a User-Drawn ActiveX trol 332
Con-Starting the Project 333Creating the User Interface 333Creating the Properties of theButton 335
Setting Up the Button’s Events 337Creating Property Pages for theButton 337
Testing the Color Button in aProgram 338
From Here… 339
15 Extending ActiveX Controls 341
Using the Ambient Object to Maintain
Properties of the Ambient Object 343
Introducing the Extender Object 344Building the Calculator Control 345Creating the Control 345Creating the Interface 346
Setting Up the Operation Property 347Coding Methods and Events 348Testing the Control 349
Creating Property Pages 350Creating Property Page Objects 350Placing Controls on the PropertyPages 351
Implementing the SelectionChanged
Trang 12Connecting the Property Page to theControl 353
Using Your Property Page 354Handling Multiple Control Selec-tions 355
Control Error Handling 355
Starting a New Class Module 362Adding Properties to the Class 362Adding Methods to the Class 365Declaring and Using Objects 366Adding Your Own Events 367Creating an ActiveX DLL 368
Creating an ActiveX Project 368Working with Multiple Projects 368
Setting the Instancing Property 371
Enums 372Creating Classes That Contain Collec-
IV Visual Basic Interfaces 379
17 Multiple Document Interface
Applications 381
Introducing MDI Applications 382
Characteristics of MDI ParentForms 383
Characteristics of MDI ChildForms 384
Creating a Simple MDI Program 384Setting Up a Parent Form 384Setting Up a Child Form 386Running the Program 387Creating Multiple Instances of aForm 388
Setting Up the Basic Form 388Creating Forms Using Object Vari-ables 390
Using the Keywords Me and
ActiveForm 390Initializing an Instance of a ChildForm 391
Working with Menus 391Managing the Children 392Using Automatic Organization 392Maintaining a Window List 393Creating a Sample Application—an MDIContact Manager 395
Creating the MDI Form 396Setting Up the Customer ChildForm 397
Creating the Search Form 398Creating the Heart of the Program 399Running the Program 400
Optimizing Your MDI Application 400Creating an MDI Application Frame-work 401
Creating the MDI Parent plate 402
Tem-The MDI Child 405From Here… 407
18 Proper Interface Design 409
Designing Effective Forms 410Keep Forms Neat and Uncluttered 410Pay Special Attention to Data EntryForms 411
Use the Right Control for the Job 412Third-Party Controls 413
Multiple Forms 413User PC Differences 415
Trang 13Dealing with User Expectations 417The List Box 417
Effective Menus 420Handling Multiple Instances of YourApplication 420
Perceived Speed 422From Here… 423
19 Using Visual Design Elements 425
Using Graphics 426Graphics Controls 426Graphics Methods 432Working with Text and Fonts 439Text Box Behavior 439Working with Fonts and Colors 441From Here… 446
V Advanced Programming Topics 525
20 Accessing the Windows API 449
Understanding the Windows API 450Using the Windows API in VisualBasic 452
Using the API Viewer 452Creating a Wrapper Function 454Creating a Wrapper Class 455Useful API Calls 457
Fun API Calls 457Finding and Controlling OtherWindows 458
Waiting on a Program to FinishRunning 461
Callbacks and Subclassing 463From Here… 467
21 Working with Files 469
File Functions in Visual Basic 470
Using Dir to Find and List Files 470File-Manipulation Functions 473
Launching Other Programs with theShell Function 475
Locating Files Relative to Your tion 475
Applica-Working with Text Files 477Sequential Text Files 477Reading from a Sequential TextFile 478
Writing to a Sequential Text File 480Random Files—Creating Your Own FileFormat 482
Creating a Record Type 482Opening a Random Access File 483
Adding Records with Put 483
Retrieving Records with Get 483
Random Access with Seek 484INI Files 484
Understanding INI Files 484Using INI Files in Visual Basic 485From Here… 487
22 Using OLE to Control Other Applications 489
Working with Word Objects 490The Microsoft Word ObjectLibrary 491
Creating Application and Document jects 492
Ob-Saving, Opening, and Printing ments 494
Docu-Working with Text 494Other Useful Features 495
Word.Basic 496Working with Excel 496Creating Excel Objects 497Setting Cell and Range Values 497Using the OLE Container Control 497Creating an Embedded Object atDesigntime 498
Creating an Embedded Object atRuntime 499
Creating a Linked Object 499From Here… 500
Trang 1423 Master’s Toolbox 501
Caller ID with Visual Basic 502
Requirements for Using the SampleProgram 502
VB Techniques You’ll Be Using 503Setting Up the CommunicationsControl 505
Checking for Calls 507Building a Screen Saver in Visual
Basic 509
Setting Up the Main Form 510Adding Animation 511Interacting with Windows 512SQL Server to Access Database Table
Export Program 512
Building the Sample Program 513Understanding the Sample Pro-gram 513
Using the Windows API to Create
Organizing the Data 529Using Indexes 534Using Queries 536Implementing Your Design 537
Using Visual Data Manager 537
Creating the Database File 538Adding a New Table 539Making Changes to the Fields in YourTable 540
Adding an Index to the Table 541Returning to the Visual Basic DesignWindow 542
Viewing or Modifying the Structure of aTable 542
Renaming or Deleting a Table 542Copying a Table 542
Creating a Database with Other Tools 543Using Microsoft Access 543
Third-Party Database Designers 543Why Use a Program Instead of Visual DataManager? 543
The Two Required Properties 548Getting Acquainted with Bound Con-trols 550
What Do These Controls Do? 550Adding Controls to Your Forms 551Using a Bound Control to DisplayData 552
Creating a Simple Application 553Setting Up the Form 553Navigating the Database 554Using Code with the Data Control 555Adding and Deleting Records 555Creating Forms Automatically 557Setting Up the Data Form Wizard 557Getting to the Source of Your Data 559Choosing the Binding Type 560Choosing Fields with the Data FormWizard 560
Control Selection 561From Here… 562
Trang 1526 Using Data Access Objects
(DAO) 565
Introduction to DAO 566Setting Up a DAO Project 567Opening an Existing Database 568Deciding Which Recordset Type toUse 569
Using Tables 570Using Dynasets 571Using Snapshots 573Using a Forward-Only Recordset 574Placing Information Onscreen 575Accessing Information from DatabaseFields 575
Displaying Data in the Sample gram 575
Pro-Positioning the Record Pointer 576
Using the Move Methods 577
Using the Bookmark Property 578
Using the Find Methods 579Setting the Current Index in aTable 581
Using the Seek Method 581
Using the PercentPosition and
AbsolutePosition Properties 584Using Filters, Indexes, and Sorts 585
Setting the Filter Property 585
Setting the Sort Property 586Creating a New Index 586Considering Programs That Modify Mul-tiple Records 587
Using Loops 587Using SQL Statements 589Understanding Other Programming Com-mands 590
Adding Records 590Editing Records 591Updating Records 591Deleting Records 592Introducing Transaction Processing 592From Here… 594
27 Using Remote Data Objects (RDO) 595
Database Access Philosophies 596Working with ODBC 596
Understanding ODBC Drivers 597Setting Up an ODBC Data Source 597The Remote Data Objects 603
Comparison of RDO to DAO 603Accessing a Database with RDO 605Using the RemoteData Control 607Comparing the RDC and the Data Con-trol 607
Setting Up the RDC 608From Here… 609
28 Using ActiveX Data Objects (ADO) 611
Introducing ADO 612Data Connection Methods 612Installation 612
Setting Up a Data Source 613Using the ADO Data Control 614Setting Up the ADO Data Control 615Connecting the ADO Data Control to aData Source 616
Displaying Data 618Changing the Record Source fromCode 619
Using the DataGrid Control 619Getting Data into the Grid 620Setting Up the DataGrid 621Splitting Up the Grid 623Customizing the Grid’s Layout 624Customizing the Grid with Code 626Using ActiveX Data Objects 627Making the Connection with ADO 627Working with Recordsets 630
The Command Object 636Disconnected Recordsets 637Creating a DisconnectedRecordset 637
Trang 16Reconnecting a Recordset 638Uses of a Disconnected Recordset 639From Here… 640
29 Creating Reports 641
Creating a Simple Report 642
Setting Up the Data Source 642Adding a Data Report to YourProject 643
Setting Up the Data Report 644Displaying the Report 647Enhancing Your Data Reports 648
Predefined Report Fields 648Adding Graphics 649Printing and Exporting 651Function Fields 652Using Crystal Reports 653
Creating a New Report 654Customizing Your Report 657Using the Crystal Reports Control 658From Here… 661
VII Visual Basic and the
The VB Scripting Engine 671Host Application 671Text Editor 672Advanced Web Tools 672The VBScript Language 673
Working with Variants Only 673Using Objects for Added Power 674Accessing the File System 675
Using VBScript in Internet Explorer 676Events and Procedures 677
Forms 679Using ActiveX Controls 681The Windows Scripting Host 682Running Scripts 683
Useful Objects and Methods 684From Here… 685
31 Active Server Pages 687
Introduction to Active Server Pages 688Active Server Pages Versus StandardHTML 688
Virtual Directories 690Creating ASP Files 693Creating a Simple ASP File 693Using Server-Side Scripting Tags 693Simple but Dynamic Web Pages 694Using Include Files 696
Database Access with Active ServerPages 697
Querying a Database 698Updating Information in a Data-base 701
The ASP Objects 704
Managing Security with the Session
The Server Object 710
The Application Object and
GLOBAL.ASA 710Using Your Own ActiveX DLL withASP 711
The IIS Application Project 711Creating an IIS Application 712Running an IIS Application 713WebClass Instancing 714Using an HTML TemplateWebItem 715
Using a Custom WebItem 717From Here… 718
Trang 1732 ActiveX Documents 719
Understanding ActiveX Documents 720What Is an ActiveX Document? 721What Are the Advantages of UsingActiveX Documents? 722Creating Your First ActiveX Docu-ment 722
Starting an ActiveX DocumentProject 723
Creating the Interface of the ment 724
Docu-Adding Code to the Document 726Testing Your ActiveX Document 726Compiling Your Document 729Exploring the UserDocument Object 729Understanding the Key Events of aUserDocument 730
Creating and Storing Properties for aUserDocument 730
Working with the Methods of theUserDocument 731
Using the Hyperlink Object in Your ment 733
Docu-Using the ActiveX Document MigrationWizard 733
Running the ActiveX Document tion Wizard 734
Migra-Looking at the Results of the Wizard’sWork 736
Creating a More Complex Document 737Programming Additional Docu-ments 737
Using and Displaying Forms from theDocument 738
Programming E-Mail 747Logging on to E-Mail 748Sending a Message 749Accessing the Contents of aMessage 750
Using the Internet Transfer Control 751Retrieving HTML 751
Transferring Files 753From Here… 755
Organizing Visual Basic’s Controls 766The Canvas of Your Programs 769Controlling Your Forms and Con-trols 770
Using the Project Window 771Where Work Gets Done 772Customizing Your Environment 773
B Packaging Your Applications 775
Compiling Your Program 776Optimizing Your Code 776Setting the Project Name, Title, andIcon 777
Preparing to Create a Setup gram 778
Pro-Packaging a Standard EXE Project 778Creating a Standard EXE Package 778
A Closer Look at the Setup cess 785
Pro-Packaging ActiveX Components 788Internet Download 788
Trang 18Scripting Options 789Files Created for the Internet 790From Here… 791
C SQL Summary 793
Defining SQL 794
What SQL Does 794The Parts of the SQL Statement 795
Using SELECT Statements 796
Defining the Desired Fields 796Specifying the Data Sources 801
Using ALL, DISTINCT, or
DISTINCTROW Predicates 802Setting Table Relationships 803Setting the Filter Criteria 806Setting the Sort Conditions 810Using Aggregate Functions 811Creating Record Groups 813Creating a Table 815Using Parameters 815SQL Action Statements 816
Using the DELETE Statement 816
Using the INSERT Statement 817
Using the UPDATE Statement 818Using Data-Definition-Language State-
Creating SQL Statements 823
Using the Visual Data Manager 823Using Microsoft Access 825Optimizing SQL Performance 825
Using Indexes 826Compiling Queries 826Keeping Queries Simple 826
Passing SQL Statements to Other DatabaseEngines 827
From Here… 827
Index 829
Trang 19Bruce Clingaman
TECHNICAL EDITORS
Mark HurstSimon Mordzynski
PRODUCTION
Marcia DeboyJennifer EarhartCynthia FieldsSusan Geiselman
Trang 20To Julia, Larry, Ben, and Brent for all of your loyal support.
- Brian Siler
To my lovely wife Tina and our beautiful daughter Lauren, for making me smile every single day You make me better at everything I do.
- Jeff Spotts
Trang 21About the Authors
Brian Siler works as a senior programmer analyst for a major hotel corporation, developing its
executive information system in Visual Basic Brian is a graduate of the University of Memphiswith a B.S in Computer Science He has developed applications using Visual Basic, C, HTML,and SQL on a variety of platforms including PCs, AS/400, UNIX, and Vax He was the co-author
of Que’s Special Edition Using Visual Basic 5, Second Edition, and Que’s Platinum Edition
Using Visual Basic 5 Brian may be contacted via e-mail at bsiler@bigfoot.com
Jeff Spotts is a Senior Business Systems Analyst for Federal Express Corporation By night,
he teaches Visual Basic programming courses at State Technical Institute at Memphis He alsodevelops custom-designed software systems for individuals and businesses His specialty iscreating database applications using Visual Basic as a front-end interface to a variety of data-base engines He has been involved with computer hardware and software since the late 1970s,and has been programming with Visual Basic since just after its introduction Jeff was a co-
author of Special Edition Using Visual Basic 5, Second Edition He may be contacted via e-mail
at jspotts@bigfoot.com
Trang 22The authors wish to acknowledge the steadying influence of our Acquisitions Editor, KellyMarshall, and our Product Director, Chris Nelson, for helping to keep this project afloat and ontrack in occasionally stormy seas We would also like to acknowledge our co-workers (bothfull-timers and the contractors who make the real money) for their continued advice and sup-port
Trang 23Tell Us What You Think!
As the reader of this book, you are our most important critic and commentator We value your
opinion and want to know what we’re doing right, what we could do better, what areas you’dlike to see us publish in, and any other words of wisdom you’re willing to pass our way
As an Executive Editor for the Programming team at Macmillan Computer Publishing, I come your comments You can fax, e-mail, or write me directly to let me know what you did ordidn’t like about this book—as well as what we can do to make our books stronger
wel-Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message.
When you write, please be sure to include this book’s title and author as well as your name andphone or fax number I will carefully review your comments and share them with the authorand editors who worked on the book
Fax: 317-817-7070E-mail: adv_prog@mcp.com
Mail: Executive Editor
ProgrammingMacmillan Computer Publishing
201 West 103rd StreetIndianapolis, IN 46290 USA
Trang 25I n this chapter
Fundamental Visual Basic Programming 2
Working with Visual Basic Components 3
Creating Application Interfaces 4
Advanced Visual Basic Programming 4
Database Programming Techniques 5
Internet Programming 5
Additional References 5
Source Code and Programs Used in This Book 6
Conventions and Special Elements Used in This Book 6
I N T R O D U C T I O N
Trang 26Congratulations! You have decided to embark on learning Visual Basic.
This is an exciting time; there never has been a better time for Visual Basic programmers.While Visual Basic has always made it easy to develop Windows programs, through the years ithas matured into a true professional development language and environment You still canquickly create Windows programs with Visual Basic, but now you also can write enterprise-level client/server programs and robust database applications In fact, the newest versioncontains several enhancements that greatly increase the power and flexibility that program-mers have to write database-enabled applications While this is enough to get you hyped upabout programming in Visual Basic, there’s even more available in Visual Basic version 6
As you know, the Internet is revolutionizing computing You also may have seen enough ofInternet programming to think that it is reserved for only a select group of programmers.Visual Basic version 5 introduced several tools that let you work more easily with the Internet.Now, in version 6, these Internet tools are even more powerful and easy to use There are toolsthat let you easily connect your programs to the Internet and include browser capabilities inyour programs In addition, over the past year or so, certain Web servers and browsers haveadded support for a special flavor of Visual Basic known as VBScript The Visual Basic knowl-edge that you acquire will translate easily into the ability to create VBScript code as well.With VBScript, you can create ActiveX documents and ActiveX controls from Visual Basic.Because ActiveX is a critically important part of Microsoft’s Internet strategy, this puts youright in the middle of the action And the really good news is that all of your ActiveX pieces can
be used in non-Internet programs as well, extending the usefulness of any ActiveX componentsyou create The ActiveX components you create can even be used by programmers workingwith other languages, such as C++
Microsoft also has integrated a special version of Visual Basic known as Visual Basic for cations (VBA) into all the components of the Microsoft Office suite, Microsoft Project, andseveral other programs Because VBA is the core language component of Visual Basic, thismeans that all your knowledge of Visual Basic can be applied to writing applications and mac-ros for other products And because Microsoft has licensed VBA to dozens of companies, youwill soon be able to write applications and macros for those programs, as well All this benefitcomes from your Visual Basic knowledge
Appli-Okay, so now you are excited about learning Visual Basic Your next question is, “What willthis book do for me?”
Fundamental Visual Basic Programming
Although this book presents a lot of material on advanced Visual Basic programming, you can’tjust jump into these topics and expect to understand them You need a good foundation fromwhich to work
In Part I of the book, “Getting Started with Visual Basic,” you are introduced to what VisualBasic can do and how to work in the development environment
Trang 27Chapter 1, “Starting Out with Visual Basic,” discusses how Visual Basic works to create dows-based computer programs and starts you out designing your first program.
Win-In Chapter 2, “Creating Your First Program,” you work step-by-step through the process ofbuilding a fully functional application in Visual Basic
Chapter 3, “Visual Basic Building Blocks,” takes you on a tour of forms and controls, which arethe fundamental components of every program you will create in Visual Basic You will see howyou can manipulate forms and controls by modifying their properties and how you can performtasks with their methods
In Chapter 4, “Using Visual Basic’s Default Controls,” you learn how to work with the group ofcontrols that is most commonly used when designing your applications
Part II, “Programming with Visual Basic,” covers the basics to get you started on your gramming adventure
Chapter 5, “Responding to the User with Event Procedures,” discusses how Visual Basic grams become interactive You’ll learn how to make your programs react to the various actionsyour users can initiate
pro-In Chapter 6, “Giving More Control to the User: Menus and Toolbars,” and Chapter 7, “UsingDialog Boxes to Get Information,” you look at how you can enhance your programs by usingmenus, toolbars, and dialog boxes These program components give your users an interfacethat is familiar because of their experience with other Windows programs The proper use ofmenus, toolbars, and dialog boxes makes your programs more intuitive to the user You alsoexamine the Event model, which is the cornerstone of programming in a Windows environ-ment
In Chapter 8, “Using Variables to Store Information,” and Chapter 9, “Visual Basic ming Fundamentals,” you are led into the world of programming commands, structures, andvariables Visual Basic is built upon the solid foundation of the BASIC language The VisualBasic language is rich in features and functions that let you write programs to handle practi-cally any task You learn how to create and use variables, and how to perform math and stringoperations Chapter 10, “Controlling the Flow of Your Program Code,” explains how to controlyour program through the use of decisions and loops and through error handling
Program-Chapter 11, “Managing Your Project: Sub Procedures, Functions, and Multiple Forms,” takesyou even further into the programming concepts that will help you enhance your programcode
Working with Visual Basic Components
Part III, “Visual Basic Program Components,” expands the fundamental knowledge that youhave gained so far by exploring various types of components you can use to enhance yourapplications Think of these components as building blocks that are more advanced than thebasic ones you learned about in preceding chapters
Trang 28Chapter 12, “Microsoft Common Controls,” introduces you to even more of the controls thatVisual Basic provides for you to use when you build your programs.
In Chapter 13, “Working with Control Arrays,” you learn more advanced techniques for usinggroups of variables to make your programs more efficient
You learn much about ActiveX components in Chapter 14, “Creating ActiveX Controls,” andChapter 15, “Extending ActiveX Controls.” These components can be used in Visual Basicprograms, Internet applications, or other ActiveX-enabled programs These chapters walk youthrough the process of creating, and then enhancing, your own ActiveX controls
Chapter 16, “Classes: Reusable Components,” teaches you how to create classes, which allowyou to take advantage of a very powerful programming feature that simplifies your work whenyou have many programs that perform similar tasks
Creating Application Interfaces
In Part IV, “Visual Basic Interfaces,” you are introduced to some concepts of designing yourprograms’ interfaces, which is what your users will interact with
In Chapter 17, “Multiple Document Interface Applications,” you learn how to create a MultipleDocument Interface (MDI) program This type of program enables your users to work withmultiple windows contained within one main window You’ll see how MDI applications differfrom those created with single forms
Chapter 18, “Proper Interface Design,” and Chapter 19, “Using Visual Design Elements,” cuss reasons why it is important to design your program before you start writing code You willalso see some of the things that make a bad user interface and learn how to avoid some of thecommon design mistakes
dis-Advanced Visual Basic Programming
Part V, “Advanced Programming Topics,” consists of several topics that that go beyond theconcepts you have already learned to focus on some very specific programming techniques.Chapter 20, “Accessing the Windows API,” shows you how to access the multitude of pre-defined programming routines available in Windows’ Applications Programming Interface Youwill see how your programs can take advantage of a vast library of code that is available to anyWindows application
Chapter 21, “Working with Files,” discusses how your programs can use different types of filesfor information storage and retrieval purposes
Chapter 22, “Using OLE to Control Other Applications,” shows you how to use OLE to haveyour programs interact with other programs, taking full advantage of the power of OLE.Chapter 23, “Master’s Toolbox,” demonstrates several standalone Visual Basic applications thatperform a variety of interesting tasks
Trang 29Database Programming Techniques
Database programs make up a large percentage of all programs in use in the business worldtoday These programs range in complexity from simple programs for managing mailing lists tocomplex programs handling reservations and billing for major corporations Part VI, “VisualBasic and Databases,” takes you through the process of building database applications to meet
a variety of needs
Chapter 24, “Database Basics,” discusses how to create and manipulate a database You tinue in Chapter 25, “The Data Control and Data-Bound Controls,” by learning how to quicklycreate applications using the Data control in conjunction with the controls that can be bound
con-to it
Chapter 26, “Using Data Access Objects (DAO),” and Chapter 27, “Using Remote Data Objects(RDO),” show you how to harness the programming power that is available for creating data-base applications
Chapter 28, “Using ActiveX Data Objects (ADO),” introduces you to Microsoft’s latest modelfor working with databases
Finally, Chapter 29, “Creating Reports,” shows you how to output data from your databaseapplications using the new Data Report Designer and Crystal Reports, a third-party reportingtool
Chapter 32, “ActiveX Documents,” extends the ActiveX concepts that you learned earlier intothe ability to create ActiveX components that can be shared in an advanced way
Chapter 33, “Visual Basic and Other Uses of the Internet,” shows you how to Web-enable yourVisual Basic applications Among other topics, you learn how to add Internet-browsing and e-mail capabilities to your programs
Trang 30Appendix B, “Packaging Your Applications,” shows you how to prepare the Visual Basic grams that you write for distribution.
pro-Appendix C, “SQL Summary,” presents the fundamentals of Structured Query Language(SQL), which is used to perform operations such as data retrieval on databases This informa-tion will be of value to you as you read the chapters that deal with accessing databases fromyour Visual Basic programs
Source Code and Programs Used in This Book
All the source code from the listings and programs included in this book is available via load from the Que—Macmillan Computer Publishing Web site You can download the listingscode to save typing time and errors as you follow examples in the book You also can obtain allthe programs built in the book and additional sample programs we’ve included
down-To access this material, follow these steps:
1 Point your browser to the following URL:
www.mcp.com/info
2 Enter the book’s ISBN as directed:
0-7897-1542-2
3 Follow the instructions to access and download the specific code or program you
are looking for
Conventions and Special Elements
Used in This Book
This book includes various conventions and special elements to highlight specific things andmake using the book easier Familiarize yourself with these conventions and elements, andallow them to enhance your reading experience
Conventions
The following list details conventions used in the book:
■ Italic type is used to emphasize the author’s points or to introduce new terms
■ Screen messages, code listings, and command samples appear in monospace type
■ URLs, newsgroups, Internet addresses, and anything you are asked to type also appear
Trang 31■ Occasionally, a code sample or listing will show a portion of program code with certainlines set in bold monospace type In such cases, the bold type signifies code you are toadd to existing code This approach enables you to see what you are supposed to add orchange in context.
■ Because of the space limitations of this book’s pages, a few code lines in this book’sexamples cannot be printed exactly as you must enter them In cases where breakingsuch a line is necessary to fit within the book’s margins, the Visual Basic continuationcharacter ( _ ) will be used at the end of the line that is broken You can leave thesecharacters out and enter the code on a single line, or just enter the characters as theyappear Visual Basic will understand the code either way
Special Elements
Certain types of information is set off in special book elements The following explanations andexamples indicate the kinds of elements you will encounter in the book
Each chapter begins with a “road map,” or list of the key topics covered in the chapter, along with
a page number so you can easily find the relevant material Then at the end of each chapter, a
“From Here…” section summarizes briefly the topics discussed in the chapter and refers you toother chapters that cover related material or extend the topic you just read about
◊See cross-references within each chapter for directions to more information on a particular topic.
Tips present short advice on a quick or often overlooked procedure
Notes provide additional information that might help you avoid problems, or offer advicethat relates to the topic ■
CAUTIONCautions warn you about potential problems that a procedure might cause, unexpected results, andmistakes to avoid
SidebarLonger discussions not integral to the flow of the chapter are set aside as sidebars Look for thesesidebars to find out even more information
T I P
N O T E
Trang 33P A R T
Getting Started with Visual Basic
Trang 34What is a Computer Program? 12
Computer Programs and Programming
Languages 13
Visual Basic Is a Smart Language 14
The Importance of Designing Your Program 14
Trang 35When people find out I know something about Visual Basic, I am often asked questions such asthe following:
■ What is Visual Basic?
■ Is Visual Basic a program?
■ What can you do with Visual Basic?
■ Why should I learn Visual Basic?
Microsoft’s Visual Basic product is defined as a programming system Simply put this
program-ming system is used to write Windows-based computer programs; it includes the Visual Basiclanguage as well as a number of tools that help you write these programs You don’t use VisualBasic as a productivity tool; you use it to create customized productivity tools By using VisualBasic to create your own customized programs, you (or your company) are not bound by thelimitations of a particular “off-the shelf” computer program; rather, you can design applications
to meet your own specific needs A good computer program should be flexible enough to fit thetask at hand, rather than having to modify your needs to fit the program
This chapter introduces you to the concept of a computer program and discusses programminglanguages as they pertain to creating your own programs The chapter concludes with someimportant considerations related to planning and designing a program This material provides
a bit of context for Chapter 2, “Creating Your First Program.”
What Is a Computer Program?
With Visual Basic, you can design programs, also known as applications, to accomplish just
about any task you can imagine Computer programs generally fall into two very broad ries—packaged and custom
catego-Packaged programs are those that you can purchase in a software store, via mail order, directfrom a manufacturer, and so on Packaged programs are predesigned to accomplish somespecific task For example, you may purchase Microsoft Word to meet your word processingneeds, Symantec’s WinFax Pro to enable your computer to send and receive faxes, or McAfee’sVirusScan to help prevent viruses from attacking your system You may also be interested ingame programs such as Broderbund’s Myst or Microsoft Flight Simulator All these programsare among the thousands upon thousands of software packages that are available for Windows-based PCs
Custom programs are usually designed for a specific purpose within a particular organization.For example, a company may need an application that tracks product orders from the time theyare placed until they are actually shipped If there is no packaged program available that meetsthe company’s specific needs, a custom program could be developed One advantage of a cus-tom program in this case is that the program can be continually modified as the company’sneeds change—packaged programs generally can’t be modified by the user
Trang 36start off as packaged programs This is quite common among vertical-market software developers—
those who create programs that are used in a specific industry For example, I have spent a number ofyears developing a software system that is used by exposition managers to manage flea markets,antique fairs, trade shows, and so on All my clients use the same basic system, but many of themhave asked for special customization features that apply to a specific situation
Another of these types of “hybrid” programs is actually meant to work as a customized interface to apackaged program, in effect enabling a user to customize a program that wasn’t designed ascustomizable! ■
One thing that all computer programs have in common, however, is that they are developedusing one or more programming languages such as Visual Basic
Computer Programs and Programming Languages
A computer program is nothing more than a set of instructions that a computer follows to complish a specific task A programming language such as Visual Basic is used to translateinstructions as we humans understand them into the steps that the computer can comprehendand follow
ac-When you get down to a computer’s most basic level, the microprocessor that is at the core ofthe computer’s functionality doesn’t understand anything other than numeric instructions Tomake matters worse, the only instructions that the processor can understand are incrediblysimplistic commands, most of which have to do with moving numbers around between
memory locations These commands that the processor understands are known as machine
language, or the most basic language that the machine (the PC) can use
Machine language is known as a low-level language, because it’s all the way down at the
processor’s level of understanding As you might imagine, writing programs in machine guage is an incredibly daunting task Fortunately, you don’t have to get down to that level tocreate computer programs Several higher-level programming languages have been developed
lan-to enable us lan-to write programs These programming languages allow programmers lan-to writeinstructions in something resembling English; the instructions are then converted into a pro-gram containing machine-language instructions that the processor can understand
Some examples of programming languages that have developed over the years include Fortranand COBOL, which are generally used with mainframe computers, as well as BASIC, Pascal, C,and C++, which are commonly used to write programs at the personal computer level
Visual Basic is a descendant of BASIC, which has been around for a number of years BASIC(Beginner’s All-Purpose Symbolic Instruction Code) was originally developed, as the nameimplies, as a language for beginners BASIC was often the first language that programmerslearned in order to become familiar with programming basics before moving on to more pow-erful languages
N O T E
Trang 37With the advent of Windows, Microsoft developed Visual Basic, which is a visual (graphical)
version of BASIC Since its introduction, Visual Basic has developed into an extremely ful application development tool, leaving its reputation as a beginners’ language far behind.One very nice feature of Visual Basic is the fact that you can use it to create a solid applicationvery quickly As you’ll see throughout this book, Visual Basic makes short work of what wouldnormally be very time-consuming programming tasks This frees up the programmer to spendhis time developing the application’s functionality, rather than spending time on mundane,repetitive programming tasks Visual Basic is often referred to as a Rapid Application Develop-ment (RAD) tool
power-Visual Basic Is a Smart Language
The main reason why Visual Basic is so popular and powerful is the same reason behind thesuccess of Windows Microsoft took a complex technology (writing computer programs) andmade it easier to use through a graphical interface Suppose you have to write a program foryour company In a visual programming environment, you can quickly design the windows thatthe user sees by drawing and arranging them just as you would lay out elements for a newspa-per In a text-based programming system, you control the user interface through programlanguage commands Common sense tells you that the visual programming method is easierfor newcomers to learn and requires less time to maintain In this case, the old adage “a picture
is worth a thousand words” truly applies
However, do not let me give you the impression that Visual Basic is just another pretty face Another key concept of Visual Basic is the ability to create and use self-contained compo-
inter-nents, or objects One type of object that you learn about ver y shortly is a Visual Basic control.
Controls are elements you can use when designing a user interface, just like the real-life trols on a car dashboard These controls can be used to display information (like a speedom-eter) or take action (like the ignition switch) The underlying operations of the car, such as therelationship between ignition, starter, and engine, are hidden from the driver; he “communi-cates” with the car through a clearly defined interface In the same way, Visual Basic controlsenable you to add features to your programs without you having to be involved in the details ofhow these features work For example, receiving input from a user of your program is assimple as drawing a control that accepts input This is a great advantage of visual programminglanguages—you can concentrate on what you want your program to do, not how to get theprogramming language to do it
con-The Importance of Designing Your Program
A college English professor of mine was once describing different types of novelists: “A tionalist author usually orders his story beginning-middle-end, a modernist might reverse thatorder, and a post-modernist would only include two of the three parts.”
Trang 38I
Part
Ch
Unfortunately, authors of computer programs don’t have that luxury Due to the structured
nature of computing, it’s critically important to design your programs before beginning to code
them Many programmers tend to want to dive in and start coding right off the bat, but youshould get into the habit of planning, even with small programs If you do nothing else, sitdown with a blank sheet of paper, make some notes about what you want the program to ac-complish, and sketch out what the user interface should look like
Please keep in mind that the strategy presented in this chapter is by no means the onlyapproach to programming, but rather one set of general guidelines Your technique, ofcourse, may be totally different ■
How Design Fits into the Programming Process
When creating a computer program, it’s important to take a structured approach Certain stepsneed to be accomplished in a certain order, and you might as well get used to doing things theright way It’s always tempting to fire up Visual Basic and dive right in to designing and codingthe program, but a little time spent with proper planning can save you a lot of headaches later
in the process
The key steps in creating a computer program are as follows:
1 Plan the program’s tasks (how it should work).
2 Design the user interface (how it should look).
3 Write the program’s code (implement steps 1 and 2).
4 Test and debug the program (including beta testing with users outside of the
develop-ment team, if appropriate)
5 Document and distribute the program (put it in use).
These steps are very generalized and definitely not all-inclusive As I discuss the sample gram in this chapter, I’ll list some steps specific to Visual Basic programming
pro-The first two steps listed define the core process of actually building the program pro-The sampleprogram in Chapter 2 provides a context for explaining some of the specifics in designing andbuilding a Visual Basic program Although you run the sample program in Chapter 2, the lasttwo steps aren’t covered until later in the book
If you are tackling a large project, breaking it down into smaller pieces will make it muchmore manageable Many of Visual Basic’s features can be used to divide up a large projectamong members of a development team ■
Program Design in a Nutshell
When starting a new project, it is tempting to just sit down and start hacking out code After all,drawing the interface and writing the program code is the most fun and creative aspect ofprogramming However, a good program starts with a solid design An in-depth flowchart
N O T E
N O T E
Trang 39might not be necessary for very small-scale projects, but on the other hand it is always a goodidea to start with a plan.
The design process should produce the following results:
■ A concise list of tasks to be performed by the program
■ Deadlines for when particular tasks need to be completed
■ Clarification of the dependence of one part of the program on another
■ The criteria for testing the program
For a program like the example in Chapter 2, the design can be a simple statement of what theprogram should accomplish For more complex programs, the design might include writtencriteria, data diagrams, flowcharts, a milestone document, and a test and acceptance plan It is
up to you and your client (the program’s user) to determine the right level of documentationthat is necessary for a given project However, you should always make sure that the design isclearly spelled out, and you should always write it down
From Here…
This chapter has exposed you to the fundamentals of writing Visual Basic programs The lowing chapters will get you started in developing your own applications:
fol-■ To step through the process of developing a Visual Basic program, see Chapter 2,
“Creating Your First Program.”
■ For an explanation of the fundamental pieces that comprise Visual Basic programs, seeChapter 3, “Visual Basic Building Blocks.”
■ For a more in-depth discussion of writing Visual Basic applications, see Chapter 9,
“Visual Basic Programming Fundamentals.”
Trang 40Creating Your First Program
Creating Your Program’s User Interface 18
Getting Information From the User 23
Changing a Form’s Properties 30
Coding Your Program’s Actions 31
Running Your Program 36
2
I n this chapter