VisualBasic2005Cookbook
ByJohnClarkCraig,TimPatrick
...............................................
Publisher:O'Reilly
PubDate:September2006
PrintISBN-10:0-596-10177-5
PrintISBN-13:978-0-59-610177-0
Pages:740
TableofContents|Index
Thisbookwillhelpyousolvemorethan300ofthemostcommonandnot-so-common
tasksthatworkingVisualBasic2005programmersfaceeveryday.Ifyou'reaseasoned
.NETdeveloper,beginningVisualBasicprogrammer,oradeveloperseekingasimpleand
clearmigrationpathfromVB6toVisualBasic2005,theVisualBasic2005Cookbook
deliversapracticalcollectionofproblem-solvingrecipesforabroadrangeofVisualBasic
programmingtasks.
TheconcisesolutionsandexamplesintheVisualBasic2005Cookbookrangefromsimple
taskstothemorecomplex,organizedbythetypesofproblemsyouneedtosolve.Nearly
everyrecipecontainsacomplete,documentedcodesampleshowingyouhowtosolvethe
specificproblem,aswellasadiscussionofhowtheunderlyingtechnologyworksandthat
outlinesalternatives,limitations,andotherconsiderations.AswithallO'ReillyCookbooks,
eachrecipehelpsyouquicklyunderstandaproblem,learnhowtosolveit,andanticipate
potentialtradeoffsorramifications.
Usefulfeaturesofthebookinclude:
Over300recipeswritteninthefamiliarO'ReillyProblem-Solution-Discussionformat
Hundredsofcodesnippets,examples,andcompletesolutionsavailablefordownload
VB6updatestoalertVB6programmerstocode-breakingchangesinVisualBasic
2005
RecipesthattargetVisualBasic2005featuresnotincludedinpreviousreleases
Codeexamplescoveringeverydaydatamanipulationtechniquesandlanguage
fundamentals
Advancedprojectsfocusingonmultimediaandmathematicaltransformationsusing
linearalgebraicmethods
Specializedtopicscoveringfilesandfilesystems,printing,anddatabases
Inaddition,you'llfindchaptersoncryptographyandcompression,graphics,andspecial
programmingtechniques.Whetheryou'reabeginneroranexpert,theVisualBasic2005
Cookbookissuretosaveyoutime,servingupthecodeyouneed,whenyouneedit.
VisualBasic2005Cookbook
ByJohnClarkCraig,TimPatrick
...............................................
Publisher:O'Reilly
PubDate:September2006
PrintISBN-10:0-596-10177-5
PrintISBN-13:978-0-59-610177-0
Pages:740
TableofContents|Index
Copyright
Dedication
Preface
Chapter1.VisualBasicProgramming
Introduction
Recipe1.1.CreatingaWindowsFormsApplication
Recipe1.2.CreatingaConsoleApplication
Recipe1.3.CreatinganASP.NETWebFormsApplication
Chapter2.TheDevelopmentEnvironment
Introduction
Recipe2.1.DiscoveringandUsingaCodeSnippet
Recipe2.2.CreatingaNewSnippet
Recipe2.3.SharingSnippets
Recipe2.4.AddingSnippetFilestoVisualStudio
Recipe2.5.GettinganApplication'sVersionNumber
Recipe2.6.LettingVisualStudioAutomaticallyUpdateanApplication'sVersion
Number
Recipe2.7.SettingtheStartupFormforanApplication
Recipe2.8.SettingtheStartuptoaSubMainProcedure
Recipe2.9.GettinganApplication'sCommandLine
Recipe2.10.TestinganApplication'sCommandLine
Recipe2.11.ObfuscatinganApplication
Recipe2.12.DeterminingifanApplicationIsRunningintheVisualStudio
Environment
Recipe2.13.AccessingEnvironmentVariables
Recipe2.14.AccessingtheRegistry
Recipe2.15.GettingSystemInformation
Recipe2.16.GettingtheUser'sName
Chapter3.ApplicationOrganization
Introduction
Recipe3.1.CreatingaCodeModule
Recipe3.2.CreatingaClass
Recipe3.3.CreatingaStructure
Recipe3.4.CreatingOtherItemTypes
Recipe3.5.CreatingObjectInstances
Recipe3.6.InitializingaClassInstancewithData
Recipe3.7.ReleasinganInstance'sResources
Recipe3.8.UsingNamespaces
Recipe3.9.SplittingaClassAcrossMultipleFiles
Recipe3.10.CreatingaFormBasedonAnotherForm
Recipe3.11.PassingandReturningStructuresandOtherObjects
Recipe3.12.CreatingandUsinganEnumeration
Recipe3.13.ConvertingBetweenNumericandStringEnumerationValues
Recipe3.14.CreatingaMethodThatAcceptsDifferentSetsofArguments
Recipe3.15.UsingStandardOperatorsforNonstandardPurposes
Recipe3.16.EnforcingStrongDataTypinginanOtherwiseWeaklyTyped
Collection
Chapter4.Forms,Controls,andOtherUsefulObjects
Introduction
Recipe4.1.CreatingandAddingControlsatRuntime
Recipe4.2.IteratingThroughAllControlsonaForm
Recipe4.3.SharingEvent-HandlerLogicAmongManyControls
Recipe4.4.WorkingwithTimers
Recipe4.5.DeterminingIfaControlCanTaketheFocus
Recipe4.6.ProgrammaticallyClickingaButton
Recipe4.7.DrawingaControl
Recipe4.8.MakingaFormtheTop-MostForm
Recipe4.9.IndicatingtheAcceptandCancelButtonsonaForm
Recipe4.10.RememberingaForm'sPositionBetweenUses
Recipe4.11.AttachingaControltotheEdgeofaForm
Recipe4.12.MovingorResizingControlsasaFormResizes
Recipe4.13.LimitingtheSizingofaForm
Recipe4.14.CenteringaForm
Recipe4.15.CreatingandMovingaBorderlessForm
Recipe4.16.CreatingaFadingForm
Recipe4.17.CreatingaNonrectangularForm
Recipe4.18.ChangingMenusatRuntime
Recipe4.19.CreatingShortcutMenus
Chapter5.Strings
Introduction
Recipe5.1.UsingaStringBuilder
Recipe5.2.CreatingaStringofNIdenticalCharacters
Recipe5.3.CreatingaStringbyRepeatingaStringNTimes
Recipe5.4.ObfuscatingaString
Recipe5.5.ConvertingBinaryDatatoaHexadecimalString
Recipe5.6.ExtractingSubstringsfromLargerStrings
Recipe5.7.ConvertingaString'sCase
Recipe5.8.ComparingStringswithCaseSensitivity
Recipe5.9.ComparingStringsWithoutCaseSensitivity
Recipe5.10.ConvertingStringstoandfromCharacterArrays
Recipe5.11.ConvertingStringstoandfromByteArrays
Recipe5.12.TallyingCharacters
Recipe5.13.CountingWords
Recipe5.14.RemovingExtraWhitespace
Recipe5.15.UsingtheCorrectEnd-of-LineCharacters
Recipe5.16.ReplacingSubstrings
Recipe5.17.InsertingaCharacterorString
Recipe5.18.InsertingaLine
Recipe5.19.Double-SpacingaString
Recipe5.20.FormattingNumbersintoStrings
Recipe5.21.TrimmingSetsofCharactersfromaString
Recipe5.22.IdentifyingandValidatingTypesofDatainaString
Recipe5.23.ConvertingStringsBetweenEncodingSystems
Recipe5.24.DeterminingaCharacter'sType
Recipe5.25.ParsingStrings
Recipe5.26.ConcatenatingStrings
Recipe5.27.SpeedingUpStringManipulation
Recipe5.28.CountingOccurrencesofaSubstring
Recipe5.29.PaddingaStringforExactLengthandAlignment
Recipe5.30.ConvertingTabstoSpaces
Recipe5.31.ReversingaString
Recipe5.32.ShufflingaString
Recipe5.33.UsingaSimpleStringEncryption
Recipe5.34.ConvertingaStringtoMorseCode
Recipe5.35.AddingStringstoanApplication'sResources
Recipe5.36.ConvertingAnyDatatoaString
Recipe5.37.UsingRegularExpressionstoExtractAllNumbers
Recipe5.38.GettingaCountofRegularExpressionMatches
Recipe5.39.GettingtheNthRegularExpressionMatch
Recipe5.40.CompilingRegularExpressionsforSpeed
Recipe5.41.UsingRegularExpressionstoValidateData
Recipe5.42.UsingRegularExpressionstoCountCharacters,Words,orLines
Recipe5.43.ConvertingaStringtoandfromBase64
Recipe5.44.SplittingaString
Recipe5.45.CreatingaStringofSpaceCharacters
Chapter6.NumbersandMath
Introduction
Recipe6.1.UsingCompactOperatorNotation
Recipe6.2.ChoosingIntegersoftheRightSizeandTypefortheJob
Recipe6.3.UsingUnsignedIntegers
Recipe6.4.SwappingTwoIntegersWithoutUsingaThird
Recipe6.5.UsingSingle-andDouble-PrecisionVariables
Recipe6.6.UsingDecimalVariablesforMaximumPrecision
Recipe6.7.ConvertingBetweenNumberTypes
Recipe6.8.RoundingNumbersAccurately
Recipe6.9.DeclaringLoopCountersWithinLoops
Recipe6.10.ConvertingBetweenRadiansandDegrees
Recipe6.11.LimitingAnglestoaRange
Recipe6.12.CreatingDouble-PrecisionPointVariables
Recipe6.13.ConvertingBetweenRectangularandPolarCoordinates
Recipe6.14.CreatingThree-DimensionalVariables
Recipe6.15.ConvertingBetweenRectangular,Spherical,andCylindrical
Coordinates
Recipe6.16.WorkingwithComplexNumbers
Recipe6.17.SolvingRightTriangles
Recipe6.18.SolvingAnyTriangle
Recipe6.19.DeterminingifaStringContainsaValidNumber
Recipe6.20.ConvertingNumberstoIntegers
Recipe6.21.CalculatingπtoThousandsofDigits
Recipe6.22.GettingaNumber'sPrimeFactors
Recipe6.23.UsingRecursiontoCalculateFactorials
Recipe6.24.ManipulatingBitswithBitwiseOperators
Recipe6.25.StoringandRetrievingBitsinaBitArray
Recipe6.26.EnhancingtheRandomNumberGenerator
Recipe6.27.GeneratingRandomIntegersinaRange
Recipe6.28.GeneratingRandomRealNumbersinaRange
Recipe6.29.GeneratingNormal-DistributionRandomNumbers
Recipe6.30.GeneratingExponential-DistributionRandomNumbers
Recipe6.31.CreatingaMatrix
Recipe6.32.InvertingaMatrix
Recipe6.33.CalculatingtheDeterminantofaMatrix
Recipe6.34.SolvingSimultaneousEquations
Recipe6.35.ListingoftheMatrixHelperClass
Chapter7.DatesandTimes
Introduction
Recipe7.1.GettingtheSystemDateandTime
Recipe7.2.AccessingtheSystem'sTimeZone
Recipe7.3.UsingSystemTicks
Recipe7.4.TimingApplicationActivities
Recipe7.5.CalculatingElapsedTimeUsingTicks
Recipe7.6.CalculatingElapsedTimewiththeStopwatch
Recipe7.7.ExtractingYear,Month,andDayNumbersfromaDateValue
Recipe7.8.ExtractingHour,Minute,andSecondNumbersfromaDateValue
Recipe7.9.CreatingaDateorTimeValuefromItsParts
Recipe7.10.FormattingDatesandTimes
Recipe7.11.ParsingandValidatingDatesandTimes
Recipe7.12.AddingtoDatesandTimes
Recipe7.13.SubtractingfromDatesandTimes
Recipe7.14.DeterminingtheNumberofDaysBetweenTwoDates
Recipe7.15.DeterminingtheDayoftheWeekforaDate
Recipe7.16.DeterminingtheDayoftheYearforaDate
Recipe7.17.DeterminingtheNumberofDaysinaMonth
Recipe7.18.UsingControlstoEnterorSelectaDate
Recipe7.19.CalculatingthePhaseoftheMoon
Recipe7.20.CreatingaCalendar
Recipe7.21.CheckingforLeapYears
Recipe7.22.DatesandTimesinISO8601Formats
Chapter8.ArraysandCollections
Introduction
Recipe8.1.FillinganArrayWhileDeclaringIt
Recipe8.2.SortingArrayElements
Recipe8.3.ReversinganArray
Recipe8.4.InsertingintoanArray
Recipe8.5.ShufflinganArray
Recipe8.6.SwappingTwoArrayValues
Recipe8.7.ResizingArraysWithoutLosingExistingValues
Recipe8.8.QuicklyCopyingPartofanArrayintoAnother
Recipe8.9.WritingaComma-Separated-ValuesFilefromaStringArray
Recipe8.10.ReadingaComma-Separated-ValuesFileintoaStringArray
Recipe8.11.UsingaMultivalueArrayInsteadofaTwo-DimensionalArray
Recipe8.12.ConvertingBetweenDelimitedStringsandArrays
Recipe8.13.FormattinganArrayasaSingleString
Recipe8.14.IteratingThroughArrayElements
Recipe8.15.PassingArraystoMethods
Recipe8.16.ReturningArraysfromFunctions
Recipe8.17.CreatingaCollection
Recipe8.18.InsertinganItemintoaCollection
Recipe8.19.DeletingaCollectionItem
Recipe8.20.IteratingThroughaCollection
Chapter9.Graphics
Introduction
Recipe9.1.CreatingGraphicsObjects
Recipe9.2.DrawingonControlsforSpecialEffects
Recipe9.3.LettingtheUserSelectaColor
Recipe9.4.WorkingwithCoordinateSystems(Pixels,Inches,Centimeters)
Recipe9.5.CreatingaBitmap
Recipe9.6.SettingaBackgroundColor
Recipe9.7.DrawingLines,Ellipses,andRectangles
Recipe9.8.DrawingLinesOnePixelWideRegardlessofScaling
Recipe9.9.ForcingaFormorControltoRedraw
Recipe9.10.UsingTransparency
Recipe9.11.ScalingwithTransforms
Recipe9.12.UsinganOutlinePath
Recipe9.13.UsingGradientsforSmoothColorChanges
Recipe9.14.DrawingBezierSplines
Recipe9.15.DrawingCardinalSplines
Recipe9.16.LimitingDisplayUpdatestoSpecificRegions
Recipe9.17.DrawingText
Recipe9.18.RotatingTexttoAnyAngle
Recipe9.19.MirroringTextontheCanvas
Recipe9.20.GettingtheHeightandWidthofaGraphicString
Recipe9.21.DrawingTextwithOutlinesandDropShadows
Recipe9.22.CalculatingaNiceAxis
Recipe9.23.DrawingaSimpleChart
Recipe9.24.CreatingOdd-ShapedFormsandControls
Recipe9.25.UsingtheRGB,HSB(HSV),andHSLColorSchemes
Recipe9.26.CreatingaRubber-BandRectangularSelection
Recipe9.27.AnimatingwithTransparency
Recipe9.28.SubstitutionsforObsoleteVisualBasic6.0Features
Chapter10.Multimedia
Introduction
Recipe10.1.PlayinganAudioFile
Recipe10.2.DisplayingImageFiles
Recipe10.3.PlayingaVideoFile
Recipe10.4.MakingYourComputerBeep
Recipe10.5.CreatinganAnimationUsingMultipleImages
Recipe10.6.CreatinganAnimationbyGeneratingMultipleBitmaps
Recipe10.7.CreatinganAnimationbyDrawingatRuntime
Recipe10.8.CreatingAnimatedSprites
Recipe10.9.ResizingandCompressingJPEGFiles
Recipe10.10.GettingJPEGExtendedInformation
Recipe10.11.CreatingThumbnails
Recipe10.12.DisplayingImagesWhileControllingStretchingandSizing
Recipe10.13.ScrollingImages
Recipe10.14.MergingTwoorMoreImages
Recipe10.15.UsingResourceImages
Recipe10.16.CapturinganImageoftheScreen
Recipe10.17.GettingDisplayDimensions
Recipe10.18.SpeedingUpImageProcessing
Recipe10.19.ConvertinganImagetoGrayscale
Recipe10.20.PerformingEdgeDetectiononanImage
Recipe10.21.FullListingoftheLockImageClass
Chapter11.Printing
Introduction
Recipe11.1.EnumeratingPrinters
Recipe11.2.Sending"Raw"DatatoaPrinter
Recipe11.3.GetDetailsAbouttheDefaultPrinter
Recipe11.4.CreatingaPrintPreview
Recipe11.5.PromptingforPrintedPageSettings
Recipe11.6.DrawingTextandGraphicstoaPrinter
Recipe11.7.DeterminingthePrintDestination
Recipe11.8.CreatingGraphPaper
Chapter12.FilesandFileSystems
Introduction
Recipe12.1.EnumeratingDrives
Recipe12.2.DeterminingifaDirectoryExists
Recipe12.3.CreatingaNewDirectory
Recipe12.4.CopyingDirectories
Recipe12.5.MovingDirectories
Recipe12.6.RenamingDirectories
Recipe12.7.ParsingFileandDirectoryPaths
Recipe12.8.SearchingIterativelyThroughDirectoriesandSubdirectories
Recipe12.9.FindingDirectoriesandFilesUsingWildcards
Recipe12.10.DeterminingIfaFileExists
Recipe12.11.GettingandSettingFileAttributes
Recipe12.12.AccessingSpecialUserandWindowsDirectories
Recipe12.13.DeterminingtheSpaceonaDrive
Recipe12.14.BrowsingforaDirectory
Recipe12.15.GettingFileInformation
Recipe12.16.UsingFile-AccessMethods
Recipe12.17.ReadingandWritingFilesasStrings
Recipe12.18.ReadingandWritingBinaryFiles
Recipe12.19.CopyingorMovingaFile
Recipe12.20.SendingaFiletotheRecycleBin
Recipe12.21.CreatingaTemporaryFile
Recipe12.22.CalculatingaChecksumforaFile
Recipe12.23.ComparingTwoFilesforEquality
Recipe12.24.LockingaFileDuringAccess
Recipe12.25.ReadingfromaFileataSpecificPosition
Recipe12.26.ReadingandWritingObjectsinaFile
Recipe12.27.CreatingaComma-Separated-ValuesFile
Chapter13.Databases
Introduction
Recipe13.1.ConnectingtoaDataProvider
Recipe13.2.IssuingSQLCommands
Recipe13.3.RetrievingResultsfromaDatabaseQuery
Recipe13.4.UsingSQLParameters
Recipe13.5.UsingStoredProcedures
Recipe13.6.UsingTransactions
Recipe13.7.StoringtheResultsofaQueryinMemory
Recipe13.8.CreatingIn-MemoryDataTablesManually
Recipe13.9.WritingIn-MemoryDataTablestoanXMLFile
Recipe13.10.ReadinganXMLFileintoIn-MemoryDataTables
Chapter14.SpecialProgrammingTechniques
Introduction
Recipe14.1.PreventingMultipleInstancesofaRunningApplication
Recipe14.2.CreatingaSimpleUserControl
Recipe14.3.DescribingUserControlProperties
Recipe14.4.StartingOtherApplicationsbyEXE,Document,orURL
Recipe14.5.WaitingforApplicationstoFinish
Recipe14.6.ListAllRunningProcesses
Recipe14.7.TerminatingaRunningProcess
Recipe14.8.PausingExecutionofaProgram
Recipe14.9.ControlApplicationsbySimulatingKeystrokes
Recipe14.10.WatchingforFileandDirectoryChanges
Recipe14.11.CreatinganIconintheSystemTray
Recipe14.12.AccessingtheClipboard
Recipe14.13.AddingTooltipstoControls
Recipe14.14.DraggingandDroppingFilestoaListBox
Recipe14.15.DraggingandDroppingBetweenListBoxControls
Recipe14.16.DisposingofObjectsAppropriately
Recipe14.17.Fine-TuningGarbageCollection
Recipe14.18.Movingthe(Mouse)Cursor
Recipe14.19.InterceptingAllKeyPressesonaForm
Recipe14.20.AccessingtheRegistry
Recipe14.21.RunningProceduresinThreads
Recipe14.22.ReadingXMLintoaTreeView
Recipe14.23.CreatinganXMLDocument
Recipe14.24.ValidatinganXMLDocument
Recipe14.25.UsingGenericCollections
Recipe14.26.CreatingaScreensaver
Recipe14.27.LocalizingtheControlsonaForm
Recipe14.28.AddingPop-upHelptoControls
Recipe14.29.MaintainingUser-SpecificSettingsBetweenUsesofanApplication
Recipe14.30.VerifyingaCreditCardNumber
Recipe14.31.CapturingaConsoleApplication'sOutput
Recipe14.32.ReadinganAssembly'sDetails
Recipe14.33.PerformingSerialI/O
Recipe14.34.RebootingtheSystem
Chapter15.Exceptions
Introduction
Recipe15.1.CatchinganException
Recipe15.2.ThrowinganException
Recipe15.3.CatchingUnhandledExceptions
Recipe15.4.DisplayingExceptionInformation
Recipe15.5.CreatingNewExceptionTypes
Recipe15.6.IgnoringExceptionsinaBlockofCode
Chapter16.CryptographyandCompression
Introduction
Recipe16.1.GeneratingaHash
Recipe16.2.EncryptingandDecryptingaString
Recipe16.3.EncryptingandDecryptingaFile
Recipe16.4.PromptingforaUsernameandPassword
Recipe16.5.HandlingPasswordsSecurely
Recipe16.6.CompressingandDecompressingaString
Recipe16.7.CompressingandDecompressingaFile
Recipe16.8.GeneratingCryptographicallySecureRandomNumbers
Recipe16.9.CompleteListingoftheCrypto.vbModule
Recipe16.10.CompleteListingoftheCompress.vbModule
Chapter17.WebDevelopment
Introduction
Recipe17.1.DisplayingWebPagesonaForm
Recipe17.2.AccessingContentWithinanHTMLDocument
Recipe17.3.GettingAllLinksfromaWebPage
Recipe17.4.GettheLocalComputer'sIPAddress
Recipe17.5.ResolvingaHostNameorIPAddressforAnotherComputer
Recipe17.6.PinginganIPAddress
Recipe17.7.UsingFTPtoDownloadFiles
Recipe17.8.CallingaWebService
Recipe17.9.SendingEmailUsingSMTP
Recipe17.10.GettingPOP3Emails
Recipe17.11.SendingaMessagetoAnotherComputer
Recipe17.12.AddingHyperlinkstoa(Desktop)Form
AbouttheAuthors
Colophon
Index
Copyright©2006O'ReillyMedia,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles(safari.oreilly.com).Formoreinformation,contact
ourcorporate/institutionalsalesdepartment:(800)998-9938or
Editor:
JohnOsborn
Indexer:
JohnBickelhaupt
Production
Editor:
ColleenGorman CoverDesigner:
Copyeditor:
RachelWheeler
Interior
Designer:
DavidFutato
Proofreader:
MaryAnne
Mayo
Illustrators:
RobertRomanoandJessamyn
Read
KarenMontgomery
PrintingHistory:
September2006:
FirstEdition.
NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
TheCookbookseriesdesignations,VisualBasic2005Cookbook,
theimageofabream,andrelatedtradedressaretrademarks
ofO'ReillyMedia,Inc.
Microsoft,MSDN,the.NETlogo,VisualBasic,VisualC++,
VisualStudio,andWindowsareregisteredtrademarksof
MicrosoftCorporation.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.
ISBN-10:0-596-10177-5
ISBN-13:978-0-596-10177-0
[M]
Dedication
InlovingmemoryofJeanieCraig(19502005).
Jeanie…Thankyouforsharingyourlife,yourspirit,
andyourlove.Ourdreamsgoon,andourloveis
eternal.
JohnCraig
Tomyparents,DonandDarla,whobothknowhow
tocook.
TimPatrick
Preface
Mostofuslearntocookatanearlyage,startingwithpeanut
butterandjellysandwichesandquicklyprogressingtomacaroni
andcheese.Butveryfewpeoplemakeittotheadvanced
cookingstage,whippingupnewculinarycreationsintheblink
ofaneyeanddazzlingallwhotastetheliteralfruitsofour
labor.Andformostofus,that'sOK.Wedon'texpectanymore
thantheordinary,themundane,onourdailyplates.
Butintheprogrammingworld,thingsaredifferent.Users
expectthemoonwhenitcomestosoftwarequality,andifyou
can'tdeliversomethingmorethanjustthemundane,you're
suretogetanearful.VisualBasic2005isagoodtoolfor
writinggreatprograms,butitisalsoverygoodatlettingpeople
writeordinarysoftware.Ordinarycookingusuallyonlyresultsin
ordinaryfood,butordinaryprogrammingcanleadtosomething
muchworse:bugs.Sohowcanyoutakeyourprogrammingto
the"masterchef"level?
Forthoseofyouwhohavelimitedcreativetalentinthekitchen,
andevenforexpertswhoarejustlookingtotrysomethingnew,
therearecookbooksgaloreatyourlocalbookstoreandsmiling
chefseachSaturdaymorningonyourlocalPBSstation.For
VisualBasicprogrammers,locatingasimilartypeofcookbook
of"programmingrecipes"hasbeensomewhatdifficultuntilnow.
Thebookyouarenowholding,VisualBasic2005Cookbook,is
therecipebookyouhavebeenlookingfor.It'schockfullof
tastysoftwaredevelopmenttidbitsthatyoucantryrightnowin
yourkitchenthatis,atyourcomputer.
Therecipesinthiscookbookwillintroduceyoutoawiderange
ofVisualBasic2005programmingtopics,fromsimplestring
andnumbermanipulationtoadvancedtopicsinvolving
animationsandmatrixtransformations.Someoftherecipes
maynotbetoyourtaste,butmanyofthemwillbejustwhat
youneed.Perhapsyou'reinthemiddleofameatyproject,and
youaren'tsurehowtocopyanexistingdirectoryfromone
placetoanother.AquicklookatRecipe12.4,"Copying
Directories,"willprovidethemissingingredientsandkeepyour
wholeprojectfromboilingover.Ormaybeyouaretryingto
formatsomecontentfortheprinter,andyouwanttodrawa
textstringata27.3-degreeangle.Ifso,youarelikelyhungry
forwhat'sinRecipe9.18,"RotatingTexttoanyAngle."
Intheworldofcooking,regularpracticebringsnoticeable
improvementsinthequalityofyourfood.Itisourbeliefthat
regularprogrammingpracticeusingtherecipesinthisbookwill
bringsimilarimprovementsinyoursoftwaredevelopmentlife.
Bonappétit!
WhoThisBookIsFor
VisualBasic2005Cookbookincludesalargevarietyofrecipes,
anditwaswrittentomeettheneedsofawiderangeof
softwaredevelopers,fromthenoviceprogrammertryingout
newcodetotheprofessionalfull-timedeveloper.Nomatter
whatyourlevelofexpertise,youwillbenefitfromtherecipes
foundineachchapter.Buteventhesimplestrecipesassumea
minimumunderstandingofVisualBasicand.NETprogramming
concepts.Ifyouareafirst-timeprogrammerstilllearningthe
basicsofloopconstructsandconditions,youmightwantto
spendalittlemoretimewithagoodtutorialbooksuchas
ProgrammingVisualBasic2005byJesseLiberty(O'Reilly)
beforeyoudiveintotherecipesfoundinthesepages.
Thisbookwaswrittenwithtwopurposesinmind.Thefirstwas
adesiretohelpreadersexpandtheirunderstandingofgeneral
andspecificprogrammingconceptsandalgorithms.Asyouread
andstudytherecipesinthisbook,youshouldbecomemore
fluentnotjustintheVisualBasiclanguage,butinthemindset
thatisrequiredtodevelophigh-qualityandstablecode.The
book'ssecondpurposewastohelpprofessionalprogrammers
(andalsorecreationalprogrammers)becomemoreproductive
byprovidingacollectionofsoftwareanswerstothequestions
thatmaystumpthemfromtimetotime.Ifeitherofthese
purposesresonateswithyouandyourprogrammingneeds,this
bookisdefinitelyforyou.
HowThisBookIsOrganized
VisualBasic2005Cookbookisprimarilyareferencebook.Each
recipeisorganizedasaproblem/solutionpair:youhavea
problem,youlocatearecipethatconcernsyourproblem,and
thenyouobtainthesolutionthroughthecodeanddiscussion
includedwiththerecipe.Ifyouaretheadventuroustype,you
canreadthroughthebookfromcovertocover,andwewill
applaudyoualltheway.Formostreaders,theskim-and-lookupmethodwillprobablyworkbetter.Theampleindexpages
shouldhelpyoufindtherecipeyouneedquickly.
Therecipesinthebookareorganizedintogeneralprogramming
topicareas,bychapter.Thefollowingminiaturetableof
contentsquicklysummarizeswhatyou'llfindineachchapter:
Chapter1,VisualBasicProgramming
Thischapterintroducesyoutothethreemaintypesof
projectsyouwilldevelopusingVisualBasic:desktop
applications,consoleapplications,andweb(ASP.NET)
applications.
Chapter2,TheDevelopmentEnvironment
Thischaptershowsyouhowtousesomeofthenewer
featuresofVisualStudioandintroducesthenewVisual
Basic2005Mynamespacefeature.Italsodiscusses
developmentissuesconcerninggeneralsystemresources
suchastheregistryandtheclipboard.
Chapter3,ApplicationOrganization
Therecipesinthischaptercoverthecoreprogramming
conceptsfoundinclasses,structures,andmodules,
includingmethodusageandoperatoroverloading.
Chapter4,Forms,Controls,andOtherUsefulObjects
Asthechaptertitleimplies,therecipesfoundheredealwith
WindowsForms(desktop)applications,withastrong
emphasisonusingthevariouscontrolsavailableforbuilding
them.
Chapter5,Strings
Thischapterincludesdozensofrecipesthatfocusonstrings
andstringmanipulation.Afewrecipesfocusonregular
expressionprocessing.
Chapter6,NumbersandMath
The.NETFramework,andbyextensionVisualBasic,
includesseveraldatatypesthateachmanipulatedifferent
sizesandrangesofnumbers.Thischapter'srecipesshow
youwaystointeractwiththosedatatypesandvalues.For
thosewhomisstheirhighschoolmathclasses,thereare
severalrecipesthatdealwithmoreadvancedmathtopics,
includinggeometryandlinearalgebra.
Chapter7,DatesandTimes
Therecipesinthischapterdemonstratehowtouseand
manipulatedateandtimevaluesandthecomponentsfrom
whichtheyarebuilt.Timingandtimerangesarealso
covered.
Chapter8,ArraysandCollections
Storingindividualdatavaluesisfine,butsometimesyou
needtostoreawholebunchofsimilarvaluesasagroup.
Thischaptershowsyouhowtodojustthatby
demonstratingvariousfeaturesofarraysandcollections.
Generics,newtoVisualBasic2005,playaprominentrolein
thischapter.
Chapter9,Graphics
Thischapterdiscussesthegraphicsfeaturesincludedwith
.NET,focusingonthemanyGDI+graphicobjectsthatlet
youdrawcomplexshapesandtextonalmostanydisplay
surface.
Chapter10,Multimedia
Movingpicturesandsoundsarethecoreofthischapter.The
recipesfoundherewillhelpyoubringactiontootherwise
staticformsandapplications.
Chapter11,Printing
Printingin.NETdependsonGDI+anditsdrawingengine.
WhilesomeoftherecipesinChapter9willbeusefulfor
generalprinting,you'llfindrecipesdealingwithother
printing-specifictopics,suchasprintpreviewsupportand
theincorporationofuser-specifiedpagesettings,inthis
chapter.
Chapter12,FilesandFileSystems
Thischapterfocusesontheinteractionbetweensoftware
andthedatastoredindiskfiles.Alsocoveredarethe
differentmethodsyoucanusetoaccessandmanagethe
filesystemsanddirectorieswheresuchfilesreside.
Chapter13,Databases
MostVisualBasicapplicationscommunicatewithoneor
moredatabasesystems.Thischapter'srecipesdemonstrate
differentmethodsyoucanuseinyourapplicationstojoin
databasesandusersthroughthemediumofyourcustom
software.
Chapter14,SpecialProgrammingTechniques
Ifyoudidn'tfinditinanotherchapter,it'shere.This
somewhatlargechaptercoverstopicsthatdidn'tfitneatly
intootherchapters.Butinouropinion,itincludessomeof
themostinterestingandtastyrecipesintheentirebook.
Chapter15,Exceptions
Errorprocessingisthefocusofthischapter.Itsrecipesdeal
specificallywithexceptionsanderrormanagementinyour
VisualBasicapplications.
Chapter16,CryptographyandCompression
Shhsomeoftherecipesinthischapteraresecret.Butit's
allrightforyoutoreadthemandusethemtoprotectand
ensuretheintegrityofthedatamanagedbyyour
application.
Chapter17,WebDevelopment
Mostoftherecipesinthisbookcanbeusedindesktopor
web-basedapplications,butthereareafewspecialtopics
thatareuniquetoASP.NETapplications.Theyappearinthis
chapter.
Mostofthebook'srecipesincludesourcecodeyoucanusein
yourownapplications.Someofthecodesamplesarerather
long,andtypingtheminwhilereadingthisbookwouldbea
chore.That'swhywe'vemadethesourcecodeformostrecipes
availableasaseparatedownloadfromtheO'ReillyMediaweb
site.Toaccessthecode,locatethisbook'swebpageat
/>
WhatYouNeedtoUseThisBook
Therecipesincludedinthisbookweredesignedspecificallyfor
usewithVisualBasic2005orlater.Whilesomeofthemore
generalrecipeswillworkwithearlierversionsofVisualBasic
.NET,manyotherrecipeswillgeneratecompile-timeorruntime
errorsifyouattempttousethemwithearlierversions.
IfyoudonotyetownacopyofVisualStudio2005,andyou
aren'tsureifyouarereadytomakethefinancialinvestmentto
obtainit,youcanusethefreeversionofthedevelopment
environment,MicrosoftVisualBasic2005ExpressEdition.
Althoughthisversiondoesnotincludeallofthefeatures
includedwiththeStandard,Professional,andEnterprise
editionsoftheproduct,youwillbeabletousemostofthe
recipesinthisbookwithit.
MicrosoftVisualBasic2005ExpressEditioncanbuildonly
desktopapplications.Ifyouarelookingforano-costtoolfor
ASP.NETapplicationdevelopment,trytheMicrosoftVisualWeb
Developer2005ExpressEdition.
BothExpressEditiontoolsareavailablefromMicrosoft'sMSDN
websiteat />TherecipesinthisbookwerealldevelopedusingVisualStudio
2005ProfessionalEdition.
ConventionsUsedinThisBook
Thefollowingtypographicalconventionsareusedinthisbook:
Plaintext
Indicatesmenutitles,menuoptions,menubuttons,and
keyboardaccelerators(suchasAltandCtrl).
Italic
Indicatesnewterms,URLs,emailaddresses,filenames,file
extensions,pathnames,anddirectories.
Constantwidth
Indicatescommands,options,switches,variables,
attributes,keys,functions,types,classes,namespaces,
methods,modules,properties,parameters,values,objects,
statements,keywords,events,eventhandlers,XMLtags,
HTMLtags,macros,thecontentsoffiles,ortheoutputfrom
commands.
Constantwidthbold
Showscommandsorothertextthatshouldbetyped
literallybytheuser;alsousedforemphasiswithincode.
Constantwidthitalic
Showstextthatshouldbereplacedwithuser-supplied
values.
Thisiconsignifiesatip,suggestion,orgeneralnote.
Thisiconindicatesawarningorcaution.