Tải bản đầy đủ (.pdf) (1,384 trang)

Programming visual c++ NET core reference 6th ed 2003

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (15.85 MB, 1,384 trang )


PUBLISHEDBY
MicrosoftPress
ADivisionofMicrosoftCorporation
OneMicrosoftWay
Redmond,Washington98052-6399
Copyright©2003byGeorgeShepherd
Allrightsreserved.Nopartofthecontentsofthisbookmaybereproducedor
transmittedinanyformorbyanymeanswithoutthewrittenpermissionofthe
publisher.
LibraryofCongressCataloging-in-PublicationData

Shepherd,George
ProgrammingwithMicrosoftVisualC++.NET,SixthEdition(CoreReference)
p.cm.
Includesindex.
ISBN0-7356-1549-7
2002

PrintedandboundintheUnitedStatesofAmerica.
123456789QWT765432
DistributedinCanadabyH.B.FennandCompanyLtd.
ACIPcataloguerecordforthisbookisavailablefromtheBritishLibrary.
MicrosoftPressbooksareavailablethroughbooksellersanddistributors
worldwide.Forfurtherinforma-tionaboutinternationaleditions,contactyour
localMicrosoftCorporationofficeorcontactMicrosoftPressInternational
directlyatfax(425)936-7329.VisitourWebsiteat
www.microsoft.com/mspress.Sendcommentsto
ActiveDirectory,ActiveX,FrontPage,Links,Microsoft,MicrosoftPress,
MSDN,Outlook,PivotChart,PivotTable,PowerPoint,SharePoint,Visio,Visual
Basic,Windows,andWindowsNTareeitherregis-teredtrademarksor


trademarksofMicrosoftCorporationintheUnitedStatesand/orothercountries.
Otherproductandcompanynamesmentionedhereinmaybethetrademarksof
theirrespectiveowners.


Theexamplecompanies,organizations,products,domainnames,e-mail
addresses,logos,people,places,andeventsdepictedhereinarefictitious.No
associationwithanyrealcompany,organization,product,domainname,e-mail
address,logo,person,place,oreventisintendedorshouldbeinferred.
Theexamplecompanies,organizations,products,domainnames,e-mail
addresses,logos,people,places,andeventsdepictedhereinarefictitious.No
associationwithanyrealcompany,organization,product,domainname,e-mail
address,logo,person,place,oreventisintendedorshouldbeinferred.
AcquisitionsEditors:JulianaAldousandDanielleBird
ProjectEditor:DeniseBankaitis
TechnicalEditor:JulieXiao


DedicatedtoSandyDastonandTedShepherd


Acknowledgments
Thispartofbookwritingisalwaysthebest—everybodyinvolvedisnearlydone
withthemanuscriptandallthat'slefttodoistothankeverybody.Becausethe
author'snameappearsonthecover,it'ssometimeseasytoforgetalltheother
folksinvolvedinaprojectaslargeasthis.Manyotherfolksgavetheirtimeand
energytothisproject,andIwishtothankyou.
ThankyouSandyDastonandTedShepherd—myfamily,foryoursupportwhile
Iwrotethisbook.
Thankyou,DeniseBankaitis.Astheprojecteditor,youkeptmegoingby

remindingmeoftheimportanceofthisproject(akeyC++referencefor.NET)
andbycoordinatingtheeffortsoftherestoftheteam,whichincludesJulieXiao,
InaChang,DanielleBird,JulianaAldous,JoelPanchot,CarlDiltz,andGina
Cassill.
Thankyou,JulieXiao,forkeepingthemanuscriptaccurate.
Thankyou,InaChang,formakingmysentencesreadable.
Thankyou,DanielleBirdandJulianaAldous.Asacquisitioneditors,yougot
thisprojectrollingandkeptitontrack.
Thankyou,JoelPanchot,formakingsuretheartinthisbooklooksgood.
Thankyou,CarlDiltzandGinaCassill,forcomposingthemanuscriptand
makingitlookgreat.
IwouldalsoliketothankthefolksatDevelopMentor,forprovidingawonderful
environmentandcommunityforthinkingandlearningaboutmoderncomputing.
Youguysarewonderful.


Introduction
ThereleaseoftheMicrosoftVisualStudio.NET(andVisualC++.NETin
particular)hasunderscoredMicrosoft’sincreasingfocusonInternet
technologies,whichareattheheartoftheMicrosoft.NETarchitecture.In
additiontosupportingthe.NETinitiative,VisualC++.NETkeepsallthe
productivity-boostingfeaturesyou’refamiliarwith,suchasEditAndContinue,
IntelliSense,AutoComplete,andcodetips.VisualC++.NETalsoincludesmany
newfeaturessuchasmanagedcodeextensionsfor.NETprogramming,support
forattributedcode,andamoreconsistentdevelopmentenvironment.These
featurestakeVisualC++.NETtoanewlevel.Thisbookwillgetyouupto
speedonthelatesttechnologiesintroducedintoVisualC++.


.NET,MFC,andATL

Thetechnologychurnwefacethesedaysisprettyimpressive.Wewentfromno
computersonourofficedesktopstonearlyeveryonehavingacomputerrunning
MS-DOSinthe1980stonearlyeveryonerunningMicrosoftWindowsbythe
mid-1990s.Thetechnologywheelisabouttoturnagain.Inthelate1990s,
everyonewasdevelopingWebsitesbyhandusingtoolssuchasrawHypertext
MarkupLanguage(HTML),CommonGatewayInterface(CGI),InternetServer
ApplicationProgrammingInterface(ISAPI)DLLs,Java,andActiveServer
Pages(ASP).InJuly2000,Microsoftannouncedtotheworldthatitwould
changeallthatbybettingthecompanyonanewtechnologydirectionnamed
.NET.
ThecurrentthrustofMicrosoftisindeed.NET.Foranumberofyears,it’sbeen
possibletobuildaWebsitebysettingupaserversomewhere,gettinganIP
address,andputtingupsomecontent.AnyonewiththeURLofyoursitecansurf
thereandcheckitout.Commercialenterpriseshavebeentakingadvantageof
theWebbypostinginformationthat’susefultocustomers.TheWebhasalso
becomeaninvaluableresearchtoolandefficientnewsbroadcastmedium.
ThecomputingworldofthenearfuturewillinvolvetheWebheavily.However,
ratherthanjusthavinghumaneyeballslookatWebsites,computersthemselves
willlookatWebsites.Thatis,WebsiteswillbeprogrammablethroughWeb
services.The.NETvisionalsopushestheresponsibilityofprovidingarichuser
interfaceouttotheserver.
WithsomuchemphasisonWebservicesandserver-baseduserinterfaces,it
mightseemthatstandaloneapplicationsandclient-sideuserinterfacescenarios
—normallytherealmoftoolssuchastheMicrosoftFoundationClassLibrary
(MFC)—willbeleftinthedust.Buttheneedforrichclient-sideuserinterfaces
isunlikelytogoaway.ManythoughtthattheadventofthePCanddistribution
technologieswouldspelltheendofcentralizedprocessingonmainframesand
minicomputers.ItturnsoutthatPCsanddistributiontechnologiesonlyaddedto
theavailablecomputingarsenal.The.NETvisionofWebservicesandrichuser
interfacesprovidedbytheserveronlyaddstotheoptionsavailabletosoftware

developers.Richclient-sideuserinterfaceswillcontinuetobeviableformany
typesofapplications,runningalongsideotherapplicationsthatuseotherkindsof
userinterfaces(suchasserver-generateduserinterfaces).


MFCisamatureandwell-understoodtechnologythat’saccompaniedbyahost
ofthird-partyextensions.Foratleastalittlewhilelonger,MFCrepresentsthe
mosteffectivewaytowritefull-featuredstandaloneapplications.Agoodportion
ofthisbookwillfocusonMFC-styledevelopment,butwe’llalsocover
WindowsForms—the.NETwaytowriteclient-sideuserinterfaces.
Ofcourse,thenextquestionis:WheredoesthisleaveCOM?COMhassolved
manyproblemsrelatedtodistributedprocessing,butithassomeserious
shortcomings—mostlycenteredaroundcomponentversioningandtype
information.Microsoft’s.NETvisionisbasedonthecommonlanguageruntime.
TheruntimetakestheplaceofCOMastheinteroperabilitystandardwithin
.NET.We’llcover.NETandthecommonlanguageruntimeindepthinPartVI
ofthisbook.
COMandthecommonlanguageruntimerepresentdifferentapproachesto
componentarchitecture,butMicrosofthastakengreatcaretoensureaseamless
coexistence.TheinteroperabilitypathbetweenCOMandtheruntimeissmooth
inmostcases.Withinthe.NETworld,youprobablywon’tfindyourselfusing
COMasacomponentarchitecture.However,youmightfindyourselfusing
ActiveTemplateLibrary(ATL)Server,whichisahigh-performancemeansof
writingWebsites.
I’veupdatedthecoverageofATLandMFCinthiseditionofthebookbecause
you’llstillfinditveryuseful.Moreimportant,I’llshowyouhowtoleverage
yourheritagecode(soundsbetterthan“legacycode,”doesn’tit?)asyoumove
intothe.NETworld.



ManagedC++vs.C#
The.NETplatformhasintroducedanewC++-likelanguagenamedC#.C#isa
curly-brace-orientedlanguagewithoutalltheheadachesofC++.MuchofC#’s
appealisduetothefactthatit’smissingsomeofthemoreproblematicelements
ofC++(suchasrawpointermanagement)whilemaintainingtheusefulfeatures
(suchasvirtualfunctions).TheC#compilereventuallyemitsmanagedcode—
thekindthatrunsunderthecommonlanguageruntime.
However,theentireworldisn’tgoingtoswitchovertoC#overnight.There’s
justtoomuchC++codeouttheretoconvert.Also,itwilltakeabitoftimefor
developerstobecomefullycomfortablewithC#.Inthemeantime,.NEThas
introducedextensionstoC++forproducingmanagedcode(codethatrunsunder
thecommonlanguageruntime).ManagedExtensionsforC++willhelpeasethe
burdenofdevelopingsoftwareforthe.NETplatformbecausetheyallowyouto
quicklyupdateexistingC++codetoworkwith.NET.Gettingthemanagedcode
featuresinC++meanssprinklingyourcodewithvariouskeywords.Intheend,
C#andmanagedC++boildowntothesameexecutablecodeoncethecompilers
aredonewithit.Inthe.NETworld,you’llprobablyfindyourselfwritingnew
componentsusingC#whileusingmanagedC++toadd.NETfeaturestoyour
existingcodebase.


.NETvs.theJavaPlatform
Inrecentyears,we’veseenagreatdealofinterestintheJavaprogramming
languageandplatform.JavabecameagreatboonforInternetdevelopersby
providingausefulmeansofdistributingclientuserinterfaces(throughJava
applets)andbyprovidingenterprisesolutionsthroughJavaEnterpriseEdition.
Now,.NEThasbecomethebestInternetdevelopmentplatformavailabletoday.
UnliketheJavaplatform,whichrequiresthatyouwriteallyourcodeusingthe
Javasyntax,.NEToftenletsyouusemultiplesyntaxestoarriveatthesame
machineinstructionset.YoucanuseC++(themainfocusofthisbook)andits

managedextensions,VisualBasic.NET,C#,andevenahostofthird-party.NET
languagestowriteyourprograms.Onceyoudevelopyoursourcecode,itis
compiledtointermediatelanguageandtheneventuallymachinecodebeforeit
runs.Because.NETcodeismanagedbyaruntime,yougetbenefitssuchas
garbagecollectionandbettercodesecurity.


WhoThisBookIsFor
VisualC++.NET,withitssophisticatedapplicationframeworkandsupportfor
.NET,isforprofessionalprogrammers,andsoisthisbook.I’llassumethat
you’reproficientintheClanguage—youcanwriteanifstatementwithout
consultingthemanual.AndI’llassumethatyou’vebeenexposedtotheC++
language—you’veatleasttakenacourseorreadabookevenifyouhaven’t
writtenmuchcode.YoumightcomparelearningC++tolearningFrench.You
canstudyFrenchinschool,butyouwon’tbeabletospeakfluentlyunlessyou
gotoaFrench-speakingcountryandstarttalkingtopeople.
TheVisualC++wizardssaveyoutimeandimproveaccuracy,butprogrammers
mustunderstandthecodethatthewizardsgenerateand,ultimately,theymust
understandthestructureoftheMFCandATLlibraries,theinnerworkingsofthe
Windowsoperatingsystem,andhow.NETworks.Iwon’tassume,however,that
youalreadyknowWindowsand.NETprogramming.I’msurethatproficientC
programmerscanlearnWindowstheMFCwayandthe.NETway.It’smore
importanttoknowC++thanitistoknowtheWin32applicationprogramming
interface(API).Youshould,however,knowhowtorunWindowsandWindowsbasedapplications.
Ifyou’realreadyexperiencedwiththeWin32APIorwiththeMFClibrary,
there’ssomethinginthisbookforyou,too.You’lllearnaboutnewfeaturessuch
astheMultipleTop-LevelInterface(MTI)andtheVisualC++.NETwizards.If
youhaven’talreadyfiguredouttheComponentObjectModel(COM),thisbook
presentssomeimportanttheorythatwillgetyoustartedonunderstanding
ActiveXcontrols.You’llalsolearnaboutATLServerandOLEDBtemplates.

Andyou’lllearnaboutC++programmingfortheInternet(includingDynamic
HTML).Finally,thisbookincludeshard-to-findcoverageofthenewmanaged
C++extensions.


What’sNotCovered
It’simpossibletocovereveryaspectofWindowsand.NETprogrammingina
singlebook.I’veexcludedtopicsthatdependonspecial-purposehardwareand
software,suchasMAPI,TAPI,andcommunicationsportaccess.I’llcoverusing
ActiveXcontrolsinanapplicationandwritingActiveXcontrolsusingATL,but
I’lldeferthein-depthcoveragetoAdamDenningandhisActiveXControls
InsideOut(MicrosoftPress,1997).I’llgetyoustartedwith32-bitmemory
management,DLLtheory,multi-threadedprogrammingtechniques,and.NET
programming,butyouneedtogetthethirdeditionofJeffreyRichter’s
ProgrammingApplicationsforMicrosoftWindows(MicrosoftPress,1997)if
you’reseriousaboutthesesubjects.AnotherusefulbookisMFCInternalsby
GeorgeShepherdandScotWingo(Addison-Wesley,1996).I’llalsogiveyoua
headstartintothe.NETspace,butI’llleavethehardcoreruntimeissuesto
JeffreyRichter’sApplied.NETProgramming(MicrosoftPress,2002).


HowtoUseThisBook
Whenyou’restartingwithVisualC++.NET,youcanusethisbookasatutorial
bygoingthroughitsequentially.Later,youcanuseitasareferencebylooking
uptopicsinthetableofcontentsorintheindex.Becauseofthetight
interrelationshipsamongmanyapplicationframeworkelements,itwasn’t
possibletocleanlyisolateeachconceptinitsownchapter,sothebookisn’t
organizedasanencyclopedia.Whenyouusethisbook,you’lldefinitelywantto
keeptheonlinehelpavailableforlookingupclassesandmemberfunctions.
Ifyou’reexperiencedwithearlierversionsofVisualC++,scanPartIforan

overviewofnewfeatures.ThenskipthebasicMFCcoverageinPartIIbutread
themoreadvancedcoverage.Also,besuretoreadthe.NETcoverage.Muchof
thesoftwaredevelopmentcommunity’seffortsareheadinginthisdirection,and
VisualC++.NETfullysupportsthe.NETprogrammingmodel.


HowThisBookIsOrganized
Asthetableofcontentsshows,thisbookhassixpartsandanappendixsection.

PartI:Windows,VisualC++.NET,andApplication
FrameworkFundamentals
Thisparttriestostrikeabalancebetweenabstracttheoryandpractical
application.AfteraquickreviewofWin32andtheVisualC++.NET
components,you’llbeintroducedtotheMFCapplicationframeworkandthe
document-viewarchitecture.You’lllookatasimple“Hello,world!”program
builtwiththeMFClibraryclassesthatrequiresonly30linesofcode.

PartII:MFCEssentials
TheMFClibrarydocumentationpresentsalltheapplicationframeworkelements
inquicksuccession,withtheassumptionthatyou’reatleastfamiliarwiththe
originalWindowsAPI.InPartIIofthisbook,you’reconfinedtoonemajor
applicationframeworkcomponent—theview,whichisreallyawindow.You’ll
learnwhatexperiencedWindowsprogrammersknowalready,butinthecontext
ofC++andtheMFClibraryclasses.You’llusetheVisualC++.NETtoolsthat
eliminatemuchofthecodingdrudgerythatearlyWindowsprogrammershadto
endure.
Thispartcoversalotofterritory,includinggraphicsprogrammingwithbitmaps,
dialogdataexchange,ActiveXcontrolusage,32-bitmemorymanagement,and
multi-threadedprogramming.Theexerciseswillhelpyoutowritereasonably
sophisticatedWindows-basedprograms,butthoseprogramswon’ttake

advantageoftheadvancedapplicationframeworkfeatures.

PartIII:MFC’sDocument-ViewArchitecture
Thispartintroducestherealcoreofapplicationframeworkprogramming—the
document-viewarchitecture.You’lllearnwhatadocumentis(somethingmuch
moregeneralthanawordprocessingdocument),andyou’llseehowtoconnect
thedocumenttotheviewthatyoustudiedinPartII.You’llbeamazed,once
you’vewrittenadocumentclass,athowtheMFClibrarysimplifiesfileI/Oand


printing.
Alongtheway,you’lllearnaboutcommandmessageprocessing,toolbarsand
statusbars,splitterframes,andcontext-sensitivehelp.You’llalsobeintroduced
totheSingleDocumentInterface(SDI),theMultipleDocumentInterface
(MDI),andtheMultipleTop-LevelInterface(MTI),whichisthecurrent
standardforWindows-basedapplicationssuchasMicrosoftWord.
PartIIIalsodiscussesdynamiclinklibraries(DLLs)writtenwiththeMFC
library.You’lllearnthedistinctionbetweenanextensionDLLandaregular
DLL.

PartIV:COM,Automation,ActiveX,andOLE
COMitselfdeservesmorethanonebook.PartIVwillgetyoustartedinlearning
fundamentalCOMtheoryfromtheMFCpointofview.You’llprogressto
Automation,whichisthelinkbetweenC++andVisualBasicforApplications
(VBA).You’llalsobecomefamiliarwithuniformdatatransfer,andyou’lllearn
thebasicsofcompounddocumentsandembeddedobjects.You’lllearnaboutthe
ATLclasslibrarysupportforOLEDB.

PartV:ProgrammingfortheInternet
ThispartstartswithatechnicalInternettutorialthatcoverstheTCP/IPprotocol

andthefundamentalsofInternetprogramming.You’lllearnhowtodevelop
serversusingATLServer,andyou’lllearnhowtoprogramforDynamicHTML.

PartVI:.NETandBeyond
TheInternetisevolvingasthenextfrontierforsoftwaredevelopment.The
InternetisnolongerjustaboutbuildingWebsitesforpeopletosimplylookat—
it’saboutWebsitesthatpeoplecanprogram.Thewire’sinplace,butuntilthe
adventofXML,noonewasbeenabletoagreeonhowtosendmethodcalls
acrosstheInternet.Twomainthrustsof.NETincludeWebservicesandserverbaseduserinterfaces..NETfullysupportsboththesenotions,alongwithanew
waytowriteclientuserinterfaces:WindowsForms.PartVIcoverswhat.NETis
allaboutandwhatyoucandowithitasaplatform.Includedherearechapters
onthecommonlanguageruntimeandmanagedcode,programmingmanaged


componentsusingC++,ASP.NET,andADO.NET.

Appendixes
AppendixAcontainsalistofmessagemapmacrosandtheircorresponding
handlerfunctionprototypes.ThecodewizardsavailablefromClassView
usuallygeneratethiscodeforyou,butsometimesyoumustmakemanual
entries.
AppendixBoffersadescriptionoftheMFCapplicationframework’sruntime
classinformationanddynamiccreationsystem.Thisisindependentofthe
runtimetypeinformation(RTTI)featurethatisnowapartofANSIC++.


Win32vs.Win16
AfewoldcomputersouttherearestillrunningWindows3.1.However,there’s
notmuchpointinspendingmoneywritingnewprogramsforobsolete
technology.ThiseditionofProgrammingwithMicrosoftVisualC++.NETis

about32-bitprogrammingforWindows98/MeandWindowsNT/2000/XPusing
theWin32API.Ifyoureallyneedtodo16-bitprogramming,Isuggestthatyou
findanoldcopyofthesecondeditionofthisbook.


SystemRequirements
Tousethisbook,you’llneedtohaveVisualC++.NETorVisualStudio.NET
installedonyourcomputer.Anycomputerthatsatisfiestheminimum
requirementsforVisualC++.NETwillworkeffectivelywithmostofthe
examplesinthisbook.BeawarethatWindowsXPHomeEditionandWindows
NT4.0don’tsupportthehostingofASP.NETWebapplicationswiththe.NET
Framework.Youcanbuildtheseprojectsontheseoperatingsystems,butyou’ll
needtouploadtheprojectstoaproperlyconfiguredhosttoexecutethem.


SampleFiles
Youcanfindthesamplefilesonthebook’scompanionCD,alongwithother
supplementalcontent.ToaccessthefilesontheCD,insertthediscinyour
computer’sCDdriveandmakeaselectionfromthemenuthatappears.Ifthe
AutoRunfeatureisnotenabledonyoursystem(ifamenudoesn’tappearwhen
youinserttheCDintothedrive),runStartCD.exeintherootfolderofthe
companionCD.Installingthesamplefilesonyourharddiskrequires
approximately60MBofdiskspace.Ifyouhavetroublerunninganyofthese
files,refertothetextinthebookthatdescribestheseprograms.
WithaconventionalC-languageprogramusingtheWindowsAPI,thesource
codefilestellthewholestory.WiththeMFClibraryapplicationframework,
thingsarenotsosimple.TheMFCApplicationWizardgeneratesmuchofthe
C++code,andtheresourcesoriginateintheresourceeditors.Theexamplesin
theearlychaptersofthisbookincludestep-by-stepinstructionsforusingthe
toolstogenerateandcustomizethesourcecodefiles.You’dbewelladvisedto

walkthroughthoseinstructionsforthefirstfewexamples—there’sverylittle
codetotype.Forthemiddlechapters,usethecodefromthesamplefilesbut
readthroughthestepstoappreciatetheroleoftheresourceeditorsandthe
wizards.Forthefinalchapters,notallthesourcecodeislisted.You’llneedto
examinethesamplefilesforthoseexamples.
Asidefromthesamplefiles,thebook’ssupplementalcontentincludestwo
eBookinstallations:astandaloneeBookinstallationandaVisualStudioHelp
eBookinstallation.ThestandaloneeBookinstallationallowsyoutoaccessan
electronicversionoftheprintbookdirectlyfromyourdesktop.TheVisual
StudioHelpeBookinstallationallowsyoutoaccessthesecondelectronic
versionoftheprintbookdirectlyfromtheVisualStudio.NEThelpsystem.


VisualStudio.NETProfessionalTrialVersion
InadditiontothecompanionCD,thisbookalsoincludesaDVDwithan
evaluationcopyofVisualStudio.NETProfessional.Thisevaluationcopycan
helpyoufollowtheexamplesinthisbookandgetyoustartedlearningVisual
C++.NET,butthesoftwarewillexpireandstopworking60daysafteryou
installit.Youcanlearnmoreaboutthisevaluationcopyanditssystem
requirementsatNote
thatnoproductsupportisavailableforthetrialversion.

WindowsFormsLibraryExtensions
OneofthebiggestsellingpointsbehindMFCduringthe1990swasthegreat
classlibrariesavailableforextendingtheframework.WithWindowsFormson
thehorizon,it’stimetokeepaneyeoutforclasslibrariesthatextendWindows
Forms.
MFCanditsextensionswereconfinedtotheC++language,butthe.NET
commonlanguageruntimeoffersavarietyofsyntaxesforwritingWindows
Forms,includingC#,VisualBasic.NET,andManagedC++.Syncfusion,a

companybasedinCary,NorthCarolina,providesawidevarietyof.NETtoolsto
makeprogrammingfor.NETeasier.Syncfusion’sEssentialSuiteincludes
componentstomakeyour.NETWindowsFormsapplicationsmoresolidand
polished.Youcandownloadafullyfunctional15-daytrialversionfrom
,aswellastheEssentialSuiteInteractiveShowcase,
anapplicationthatshowsseveralSyncfusioncomponentsinaction.The
componentsrununderthecommonlanguageruntime,sotheyworkwith
ManagedC++aswellaswithC#andVisualBasic.NET.


MicrosoftPressSupportInformation
Everyefforthasbeenmadetoensuretheaccuracyofthisbookandthecontents
ofthecompanionCD.MicrosoftPressprovidescorrectionsforbooksat
/>ToconnectdirectlytotheMicrosoftPressKnowledgeBaseandsubmitaquery,
goto: />Ifyouhavecomments,questions,orideasregardingthisbookorthecompanion
contentorquestionsthatarenotansweredbyqueryingtheKnowledgeBase,
pleasesendthemtoMicrosoftPressusingpostalmailore-mail:
MicrosoftPress
Attn:ProgrammingwithMicrosoftVisualC++.NETEditor
OneMicrosoftWay
Redmond,WA98052-6399

Notethatproductsupportisnotofferedthroughtheabovemailaddresses.For
MicrosoftVisualC++.NETsupportinformation,pleasevisittheMicrosoft
SupportWebsiteat:.


Chapter1
WindowsandVisualC++.NET
Intheearlynineties,thebattlewasforthedesktopoperatingsystem.Nowthat

battleisover,andMicrosoftWindowsrunsonthevastmajorityofpersonal
computersystems.Thischaptersummarizesthelow-levelWindows
programmingmodel(Win32,inparticular)andshowsyouhowtheMicrosoft
VisualC++.NETcomponentsworktogethertohelpyouwriteapplicationsfor
Windows.Alongtheway,youmightlearnsomenewthingsaboutWindowsas
well.


TheWindowsProgrammingModel
Nomatterwhichdevelopmenttoolsyouuse,programmingforWindowsis
differentfromold-stylebatch-orientedortransaction-orientedprogramming.To
getstarted,youneedtoknowsomeWindowsfundamentals.Asaframeof
reference,we’llusethewell-knownMS-DOSprogrammingmodel.Evenifyou
don’tcurrentlyprogramforplainMS-DOS,you’reprobablyfamiliarwithit.

MessageProcessing
WhenyouwriteanMS-DOS–basedapplicationinC,theonlyabsolute
requirementisafunctionnamedmain.Theoperatingsystemcallsmainwhen
theuserrunstheprogram,andfromthatpointon,youcanuseanyprogramming
structureyouwant.Ifyourprogramneedstogetuserkeystrokesorotherwise
useoperatingsystemservices,itcallsanappropriatefunction,suchasgetchar,
orperhapsusesacharacter-basedwindowinglibrary.
WhentheWindowsoperatingsystemlaunchesaprogram,itcallstheprogram’s
WinMainfunction.SomewhereyourapplicationmusthaveWinMain,which
performssomespecifictasks.Itsmostimportanttaskiscreatingtheapplication’s
mainwindow,whichmusthaveitsowncodetoprocessmessagesthatWindows
sendsit.AnessentialdifferencebetweenaprogramwrittenforMS-DOSanda
programwrittenforWindowsisthatanMS-DOS–basedprogramcallsthe
operatingsystemtogetuserinputbutaWindows-basedprogramprocessesuser
inputviamessagesfromtheoperatingsystem.

NOTEManydevelopmentenvironmentsforWindows,including
VisualC++.NETwithMicrosoftFoundationClass(MFC)library
version7.0,simplifyprogrammingbyhidingtheWinMainfunctionand
structuringthemessage-handlingprocess.WhenyouusetheMFC
library,youneednotwriteaWinMainfunction,butitisessentialthat
youunderstandthelinkbetweentheoperatingsystemandyour
programs.
MostmessagesinWindowsarestrictlydefinedandapplytoallprograms.For
example,aWM_CREATEmessageissentwhenawindowisbeingcreated,a


WM_LBUTTONDOWNmessageissentwhentheuserpressestheleftmouse
button,aWM_CHARmessageissentwhentheusertypesacharacter,anda
WM_CLOSEmessageissentwhentheuserclosesawindow.Allmessageshave
two32-bitparametersthatconveyinformationsuchascursorcoordinates,key
code,andsoforth.WindowssendsWM_COMMANDmessagestothe
appropriatewindowinresponsetousermenuchoices,dialogboxbuttonclicks,
andsoon.Commandmessageparametersvarydependingonthewindow’s
menulayout.Youcandefineyourownmessages,whichyourprogramcansend
toanywindowonthedesktop.Theseuser-definedmessagesactuallymakeC++
lookalittlelikeSmalltalk.
Don’tworryyetabouthowthesemessagesareconnectedtoyourcode.That’s
thejoboftheapplicationframework.Beaware,though,thattheWindows
messageprocessingrequirementimposesalotofstructureonyourprogram.
Don’ttrytoforceyourWindows-basedprogramstolooklikeyouroldMS-DOS
programs.Studytheexamplesinthisbook,andthenbepreparedtostartfresh.

TheWindowsGraphicsDeviceInterface
ManyMS-DOSprogramswritedirectlytothevideomemoryandtheprinter
port.Thedisadvantageofthistechniqueistheneedtosupplydriversoftwarefor

everyvideoboardandeveryprintermodel.Windowsintroducedalayerof
abstractioncalledtheGraphicsDeviceInterface(GDI).Windowsprovidesthe
videoandprinterdrivers,soyourprogramdoesn’tneedtoknowthetypeof
videoboardandprinterattachedtothesystem.Insteadofaddressingthe
hardware,yourprogramcallsGDIfunctionsthatreferenceadatastructurecalled
adevicecontext.Windowsmapsthedevicecontextstructuretoaphysicaldevice
andissuestheappropriateinput/outputinstructions.TheGDIisalmostasfastas
directvideoaccess,anditallowsdifferentapplicationswrittenforWindowsto
sharethedisplay.
Laterinthebook,we’lllookatGDI+.Asyoumightguess,GDI+isthe
successortoGDI.TheservicesofGDI+areexposedthroughasetofC++
classesdeployedasmanagedcode—thatis,coderunningunderthecommon
languageruntime.GDI+introducesseveralenhancementsoverclassicGDI,
includinggradientbrushes,cardinalsplines,independentpathobjects,scalable
regions,alphablending,andmultipleimageformats.


Resource-BasedProgramming
Tododata-drivenprogramminginMS-DOS,youmusteithercodethedataas
initializationconstantsorprovideseparatedatafilesforyourprogramtoread.
WhenyouprogramforWindows,youstoredatainaresourcefileusinga
numberofestablishedformats.Thelinkercombinesthisbinaryresourcefile
withtheC++compiler’soutputtogenerateanexecutableprogram.Resource
filescanincludebitmaps,icons,menudefinitions,dialogboxlayouts,and
strings.Theycanevenincludecustomresourceformatsthatyoudefine.
Youuseatexteditortoeditaprogram,butyougenerallyuseWYSIWYG(what
youseeiswhatyouget)toolstoeditresources.Ifyou’relayingoutadialogbox,
forexample,youselectelements(buttons,listboxes,andsoforth)fromanarray
oficonscalledacontrolpalette,andyoupositionandsizetheelementswiththe
mouse.VisualC++.NEThasgraphicsresourceeditorsforallstandardresource

formats.

MemoryManagement
WitheachnewversionofWindows,memorymanagementgetseasier.Ifyou’ve
heardhorrorstoriesaboutlockingmemoryhandles,thunks,andburgermasters,
don’tworry.That’sallinthepast.Todayyousimplyallocatethememoryyou
need,andWindowstakescareofthedetails.Chapter10describescurrent
memorymanagementtechniquesforWin32,includingvirtualmemoryand
memory-mappedfiles.

Dynamic-LinkLibraries
IntheMS-DOSenvironment,allofaprogram’sobjectmodulesarestatically
linkedduringthebuildprocess.Windowsallowsdynamiclinking,whichmeans
thatspeciallyconstructedlibrariescanbeloadedandlinkedatruntime.Multiple
applicationscansharedynamic-linklibraries(DLLs),whichsavesmemoryand
diskspace.Dynamiclinkingincreasesprogrammodularitybecauseyoucan
compileandtestDLLsseparately.
DesignersoriginallycreatedDLLsforusewiththeClanguage,andC++has
addedsomecomplications.TheMFClibrarydeveloperssucceededincombining
alltheapplicationframeworkclassesintoafewready-builtDLLs.Thismeans


×