If you're a seasoned .NET developer, beginning Visual Basic programmer, or a developer seeking a simple and clear migration path from VB6 to Visual Basic 2005, the Visual Basic 2005 Cook
Trang 1By John Clark Craig, Tim Patrick
Publisher: O'Reilly Pub Date: September 2006 Print ISBN-10: 0-596-10177-5 Print ISBN-13: 978-0-59-610177-0 Pages: 740
Table of Contents | Index
This book will help you solve more than 300 of the most common and not-so-common tasks that working Visual Basic 2005 programmers face every day If you're a seasoned NET developer, beginning Visual Basic programmer, or a developer seeking a simple and
clear migration path from VB6 to Visual Basic 2005, the Visual Basic 2005 Cookbook
delivers a practical collection of problem-solving recipes for a broad range of Visual Basic programming tasks.
The concise solutions and examples in the Visual Basic 2005 Cookbook range from simple
tasks to the more complex, organized by the types of problems you need to solve Nearly every recipe contains a complete, documented code sample showing you how to solve the specific problem, as well as a discussion of how the underlying technology works and that outlines alternatives, limitations, and other considerations As with all O'Reilly Cookbooks, each recipe helps you quickly understand a problem, learn how to solve it, and anticipate potential tradeoffs or ramifications.
Useful features of the book include:
Over 300 recipes written in the familiar O'Reilly Problem-Solution-Discussion format
Hundreds of code snippets, examples, and complete solutions available for download VB6 updates to alert VB6 programmers to code-breaking changes in Visual Basic 2005
Recipes that target Visual Basic 2005 features not included in previous releases Code examples covering everyday data manipulation techniques and language
Trang 2Advanced projects focusing on multimedia and mathematical transformations using linear algebraic methods
Specialized topics covering files and file systems, printing, and databases
In addition, you'll find chapters on cryptography and compression, graphics, and special
programming techniques Whether you're a beginner or an expert, the Visual Basic 2005
Cookbook is sure to save you time, serving up the code you need, when you need it.
Trang 3By John Clark Craig, Tim Patrick
Publisher: O'Reilly Pub Date: September 2006 Print ISBN-10: 0-596-10177-5 Print ISBN-13: 978-0-59-610177-0 Pages: 740
Trang 14Printed in the United States of America
Published by O'Reilly Media, Inc., 1005 Gravenstein HighwayNorth, Sebastopol, CA 95472
O'Reilly books may be purchased for educational, business, orsales promotional use Online editions are also available for
Robert Romano and Jessamyn Read
Trang 15Visual Studio, and Windows are registered trademarks of
Microsoft Corporation
Many of the designations used by manufacturers and sellers todistinguish their products are claimed as trademarks Wherethose designations appear in this book, and O'Reilly Media, Inc.was aware of a trademark claim, the designations have beenprinted in caps or initial caps
While every precaution has been taken in the preparation of thisbook, the publisher and authors assume no responsibility forerrors or omissions, or for damages resulting from the use ofthe information contained herein
ISBN-10: 0-596-10177-5
ISBN-13: 978-0-596-10177-0
[M]
Trang 16In loving memory of Jeanie Craig (19502005).
Jeanie… Thank you for sharing your life, your spirit, and your love Our dreams go on, and our love is eternal.
Trang 17Most of us learn to cook at an early age, starting with peanutbutter and jelly sandwiches and quickly progressing to macaroniand cheese But very few people make it to the advanced
cooking stage, whipping up new culinary creations in the blink
of an eye and dazzling all who taste the literal fruits of our
labor And for most of us, that's OK We don't expect any morethan the ordinary, the mundane, on our daily plates
But in the programming world, things are different Users
expect the moon when it comes to software quality, and if youcan't deliver something more than just the mundane, you'resure to get an earful Visual Basic 2005 is a good tool for
writing great programs, but it is also very good at letting peoplewrite ordinary software Ordinary cooking usually only results inordinary food, but ordinary programming can lead to somethingmuch worse: bugs So how can you take your programming tothe "master chef" level?
For those of you who have limited creative talent in the kitchen,and even for experts who are just looking to try something new,there are cookbooks galore at your local bookstore and smilingchefs each Saturday morning on your local PBS station For
The recipes in this cookbook will introduce you to a wide range
of Visual Basic 2005 programming topics, from simple stringand number manipulation to advanced topics involving
animations and matrix transformations Some of the recipesmay not be to your taste, but many of them will be just what
Trang 18place to another A quick look at Recipe 12.4, "Copying
Directories," will provide the missing ingredients and keep yourwhole project from boiling over Or maybe you are trying toformat some content for the printer, and you want to draw atext string at a 27.3-degree angle If so, you are likely hungryfor what's in Recipe 9.18, "Rotating Text to any Angle."
In the world of cooking, regular practice brings noticeable
improvements in the quality of your food It is our belief thatregular programming practice using the recipes in this book willbring similar improvements in your software development life.Bon appétit!
Who This Book Is For
Visual Basic 2005 Cookbook includes a large variety of recipes,
and it was written to meet the needs of a wide range of
software developers, from the novice programmer trying outnew code to the professional full-time developer No matter
what your level of expertise, you will benefit from the recipesfound in each chapter But even the simplest recipes assume aminimum understanding of Visual Basic and NET programmingconcepts If you are a first-time programmer still learning thebasics of loop constructs and conditions, you might want to
Trang 19by providing a collection of software answers to the questionsthat may stump them from time to time If either of these
purposes resonates with you and your programming needs, thisbook is definitely for you
How This Book Is Organized
Visual Basic 2005 Cookbook is primarily a reference book Each
recipe is organized as a problem/solution pair: you have a
problem, you locate a recipe that concerns your problem, andthen you obtain the solution through the code and discussionincluded with the recipe If you are the adventurous type, youcan read through the book from cover to cover, and we will
applaud you all the way For most readers, the skim-and-look-up method will probably work better The ample index pagesshould help you find the recipe you need quickly
The recipes in the book are organized into general programmingtopic areas, by chapter The following miniature table of
Trang 20development issues concerning general system resourcessuch as the registry and the clipboard
emphasis on using the various controls available for buildingthem
Chapter 5, Strings
This chapter includes dozens of recipes that focus on stringsand string manipulation A few recipes focus on regular
expression processing
Chapter 6, Numbers and Math
The NET Framework, and by extension Visual Basic,
includes several data types that each manipulate differentsizes and ranges of numbers This chapter's recipes showyou ways to interact with those data types and values Forthose who miss their high school math classes, there areseveral recipes that deal with more advanced math topics,
Trang 21Chapter 7, Dates and Times
The recipes in this chapter demonstrate how to use and
manipulate date and time values and the components fromwhich they are built Timing and time ranges are also
covered
Chapter 8, Arrays and Collections
Storing individual data values is fine, but sometimes youneed to store a whole bunch of similar values as a group.This chapter shows you how to do just that by
demonstrating various features of arrays and collections.Generics, new to Visual Basic 2005, play a prominent role inthis chapter
Chapter 9, Graphics
This chapter discusses the graphics features included with.NET, focusing on the many GDI+ graphic objects that letyou draw complex shapes and text on almost any displaysurface
Chapter 10, Multimedia
Moving pictures and sounds are the core of this chapter Therecipes found here will help you bring action to otherwisestatic forms and applications
Trang 22Printing in NET depends on GDI+ and its drawing engine.While some of the recipes in Chapter 9 will be useful forgeneral printing, you'll find recipes dealing with other
printing-specific topics, such as print preview support andthe incorporation of user-specified page settings, in thischapter
Chapter 12, Files and File Systems
This chapter focuses on the interaction between softwareand the data stored in disk files Also covered are the
different methods you can use to access and manage thefile systems and directories where such files reside
Chapter 13, Databases
Most Visual Basic applications communicate with one ormore database systems This chapter's recipes demonstratedifferent methods you can use in your applications to joindatabases and users through the medium of your customsoftware
Chapter 14, Special Programming Techniques
If you didn't find it in another chapter, it's here This
somewhat large chapter covers topics that didn't fit neatlyinto other chapters But in our opinion, it includes some ofthe most interesting and tasty recipes in the entire book
Trang 23Error processing is the focus of this chapter Its recipes dealspecifically with exceptions and error management in yourVisual Basic applications
Chapter 16, Cryptography and Compression
Shhsome of the recipes in this chapter are secret But it'sall right for you to read them and use them to protect andensure the integrity of the data managed by your
application
Chapter 17, Web Development
Most of the recipes in this book can be used in desktop orweb-based applications, but there are a few special topicsthat are unique to ASP.NET applications They appear in thischapter
Most of the book's recipes include source code you can use inyour own applications Some of the code samples are ratherlong, and typing them in while reading this book would be achore That's why we've made the source code for most recipesavailable as a separate download from the O'Reilly Media website To access the code, locate this book's web page at
http://www.oreilly.com/catalog/vb2005ckbk/
What You Need to Use This Book
The recipes included in this book were designed specifically foruse with Visual Basic 2005 or later While some of the more
Trang 24If you do not yet own a copy of Visual Studio 2005, and youaren't sure if you are ready to make the financial investment toobtain it, you can use the free version of the development
Both Express Edition tools are available from Microsoft's MSDNweb site at http://msdn.microsoft.com/express/
Italic
Trang 25Constant width
Indicates commands, options, switches, variables,
attributes, keys, functions, types, classes, namespaces,methods, modules, properties, parameters, values, objects,statements, keywords, events, event handlers, XML tags,HTML tags, macros, the contents of files, or the output fromcommands
Trang 26This book is here to help you get your job done In general, youmay use the code in this book in your programs and
documentation You do not need to contact us for permissionunless you're reproducing a significant portion of the code Forexample, writing a program that uses several chunks of codefrom this book does not require permission Selling or
distributing a CD-ROM of examples from O'Reilly books does
require permission Answering a question by citing this bookand quoting example code does not require permission
Incorporating a significant amount of example code from this
book into your product's documentation does require
permission
We appreciate, but do not require, attribution An attributionusually includes the title, author, publisher, and ISBN For
example: "Visual Basic 2005 Cookbook by Tim Patrick and John
10177-0."
Clark Craig Copyright 2006 O'Reilly Media, Inc., 978-0-596-If you feel your use of code examples falls outside fair use orthe permission given above, feel free to contact us at
permissions@oreilly.com
Comments and Questions
Please address comments and questions concerning this book tothe publisher:
O'Reilly Media, Inc
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
Trang 27(707) 829-0104 (fax)
We have a web page for this book that lists errata, examples,and any additional information You can access this page at:
http://www.oreilly.com/catalog/vb2005ckbk/
To comment or ask technical questions about this book, sendemail to:
bookquestions@oreilly.com
For more information about our books, conferences, ResourceCenters, and the O'Reilly Network, see our web site at:
http://www.oreilly.com
Safari® Enabled
When you see a Safari Enabled icon on the cover ofyour favorite technology book, that means the book is availableonline through the O'Reilly Network Safari Bookshelf
Safari offers a solution that's better than e-books It's a virtuallibrary that lets you easily search thousands of top tech books,cut and paste code samples, download chapters, and find quickanswers when you need the most accurate, current information.Try it for free at http://safari.oreilly.com
Acknowledgments
For those of you who plan on writing a computer book someday, we wholeheartedly recommend O'Reilly Media for your
Trang 28O'Reilly aren't just book publishers, they are technology lovers.They actually understand and try out the code included in theirbooks
The authors wish to especially thank John Osborn and RalphDavis for their constant editorial devotion and dedication to thisbook, from the first glimmer of interest during the "idea phase,"
to the final push to get every word just where it needed to be.Also essential were Caitrin McCollough and the dozens of othertechnically adept people who had their fingers in this project
Jay Schmelzer and Steve Saunders provided regular and
valuable feedback on all technical aspects of the book If youfind any problem with any of the code in this book, it was
probably something we added in after they had a chance toreview each chapter
From Tim Patrick
Once again my family has been incredibly patient with me as Ispent time playing with the computer You would think that
there would be a limit on how many times a person can hear
me say "Just one more paragraph," and still love me But theydo
My beautiful wife Maki is certainly the best wife anyone couldfind, and I sometimes feel sad for all of the other husbands whohave to settle for less than what I have And when I also takeinto account my son Spencer, who is just becoming a fourthgrader as I write this, I truly know that I am one blessed man
It is a miracle of God that such joy comes through the two
people I get to be with each and every day
Although I see her much less often, my agent Claudette Moore
Trang 29Thanks to John Craig, John Osborn, Ralph Davis, and the team
at O'Reilly for trusting me with a portion of this book's content
As everyone in the computer industry already knew, O'ReillyMedia is a top-notch group producing great technical resources
From John Clark Craig
This has been a bittersweet year of transition for me, startingwith the unexpected death of Jeanie, my wonderful wife of 34years, soon after the first few chapters were authored Jeaniewas always supportive of my book writing, and she was veryexcited about this one I know she still is
My family and friends have been a steadfast source of joy,
inspiration, and support throughout this year Dakotah and
Makayla are the best grandkids a guy could ever hope for, andall my parents, siblings, and in-laws have been there for mewhen I needed them most
My fiancée EJ Thornton has been an absolute angel, and a
bright guiding light in my life for the past few months Thankyou EJ for bringing a renewal of meaning and purpose to mylife, and thank you Jeanie for blessing us and for bringing ustogether!
I owe a huge debt of gratitude to Tim Patrick for jumping inwith his tremendous talent to help create this book, to RalphDavis for his great editorial skills and emotional support
(Ralph's wife passed away recently, too), to John Osborn for hisnearly infinite patience, understanding, and guidance on thisproject, and to everyone else involved at O'Reilly
Finally, I want to thank Microsoft for creating an excellent set of
Trang 30Express "free forever" to the public was a smart win/win
decision for us all
Trang 32
When Visual Basic 1.0 was introduced in the early 1990s, itgreatly simplified Windows application development VisualBasic 2005continues the tradition by providing a programmer-friendly environment in which you can write powerful desktop,web-based, and mobile applications quickly and easily
In this introductory chapter you'll see just how easy it is towrite a variety of applications by developing a simple
application in three Visual Basicsupported flavors: a desktopapplication (" Windows Forms"), a console application, and aweb-based application ("Web Forms" via ASP.NET)
The three recipes in this chapter are meant to be read as a set.The first recipe, which focuses on Windows Forms, includesadditional background information concerning the logic of theapplication developed in all three recipes Be sure to read thisrecipe first
Trang 33
Application
Problem
You want to develop a Windows Forms application that convertsbetween the Fahrenheit, Celsius, and kelvin temperature
systems
Solution
Sample code folder: Chapter 01 \Forms Version
Create a Windows Forms application, and add the appropriatecontrols and logic
Discussion
Start Visual Studio 2005, and then create a new project TheStart Page includes a link to do this, or you can use the File New Project menu command The New Project dialog appears,
as shown in Figure 1-1
Figure 1-1 Visual Studio's New Project dialog
Trang 34selected application type You could choose the Blank Solutiontemplate and work your way up to the functionality providedthrough the Windows Application template, but that's more than
we need to accomplish right now
Select Visual Basic (or the Windows entry under Visual Basic) inthe "Project types" field and Windows Application in the
Templates field, enter the name of your project in the Namefield (let's call ours "FormConvertTemp"), and click the OK
button
As Visual Studio works behind the scenes to configure the initialproject features, let's take a few minutes to review some highschool science The three temperature systems in this
Trang 35measure heat in the various scientific disciplines:
In the Celsius (or Centigrade) scale, water freezes at 0°Cand reaches its boiling point at 100°C This makes it a
pretty simple measurement system, at least where water isconcerned Celsius is used as the common temperature
measurement system in most countries
The Fahrenheit system uses the environment of its founder,Gabriel Fahrenheit, as its basis for measurement 0°F, atthe lower end of the 0-to-100 scale, is rumored to be thecoldest temperature that Fahrenheit measured near his
home one winter The 100°F mark is based on his own bodytemperature This system, used in America and a few otherlocations, is especially convenient if you are a German
scientist with a slight fever
The kelvin system uses the same scale size as the Celsius
system, but places 0K at absolute zero, the theoretical
temperature at which all super-quantum molecular activityceases 0K is equivalent to-273.15°C, and all other
temperatures on the kelvin scale are converted to Celsiusthrough a simple adjustment of that same 273.15°value
Trang 36The form you see represents the initial main form of your
application It is part of a project, a collection of files usually tied to a single target, such as an application, a dynamic-link
library, or some other output In Windows Forms projects, thetarget is an executable file (with an EXE file extension) that
contains a compiled NET application All of the files in your
project are listed in the Solution Explorer, one of the standardtool windows in Visual Studio (Figure 1-3)
The top edge of the Solution Explorer includes a set of toolbarbuttons that help you "explore the solution." The most
interesting of these buttons is the second from left, the ShowAll Files button Clicking this button toggles the view of filesincluded in your project Most of the files included in your
application are hidden from view by default Visual Studio does
an amazing amount of work behind the scenes, and most of thiswork is stored in hidden project files Most of these files containcode automatically generated by Visual Studio as you design
Trang 37ApplicationEvents.vb, do contain code that you can update
manually, but most of your development time will focus on thefiles that are always displayed
Figure 1-3 The Visual Studio Solution Explorer
The main area of the form is its design surface, on which you place (or "draw") controls The Toolbox (Figure 1-4) containsthe controls that you can add to your form; it's just one of themany "tool windows" available within Visual Studio If it's notalready displayed, open the Toolbox now through the View Toolbox menu command
Figure 1-4 Partial view of the Visual Studio
Toolbox
Trang 38Window menu command
Figure 1-5 Partial view of the Properties window
Trang 39in the Properties window based on the property name in the leftcolumn, and use the mouse or keyboard to modify its value inthe right column Some properties can be expanded into distinctsub-properties using the plus sign (+) to the left of the propertyname And while most properties accept simple text values,others have mouse-friendly drop-down editors
Before adding controls to our form, let's configure the
properties of the form itself Using the Properties window, setthe form's properties as shown in Table 1-1 This table lists onlythose properties that deviate from their default settings
Table 1-1 Application form property changes
FormBorderStyle FixedSingle
Trang 40temperatures
One Button control to initiate the conversion
Use the Toolbox to select and add controls to the form Add acontrol either by double-clicking on the control in the Toolbox or
by selecting the control in the Toolbox and then "drawing" it onthe surface of the form using the mouse Go ahead and add thethree RadioButton controls, three TextBox controls, and one Buttoncontrol, and arrange them so that your form resembles Figure1-6 You may also want to resize the form to visually fit the
contained controls
Figure 1-6 Project form with included controls