外文翻译 - Visual C++ MFC 简要介绍_第1页
外文翻译 - Visual C++ MFC 简要介绍_第2页
外文翻译 - Visual C++ MFC 简要介绍_第3页
外文翻译 - Visual C++ MFC 简要介绍_第4页
外文翻译 - Visual C++ MFC 简要介绍_第5页
已阅读5页,还剩15页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

0外文原文IntroductiontoMFCProgrammingwithVisualC+Version6.xbyMarshallBrainVisualC+ismuchmorethanacompiler.Itisacompleteapplicationdevelopmentenvironmentthat,whenusedasintended,letsyoufullyexploittheobjectorientednatureofC+tocreateprofessionalWindowsapplications.Inordertotakeadvantageofthesefeatures,youneedtounderstandtheC+programminglanguage.IfyouhaveneverusedC+,pleaseturntotheC+tutorialsintheC/C+Tutorialspageforanintroduction.YoumustthenunderstandtheMicrosoftFoundationClass(MFC)hierarchy.ThisclasshierarchyencapsulatestheuserinterfaceportionoftheWindowsAPI,andmakesitsignificantlyeasiertocreateWindowsapplicationsinanobjectorientedway.ThishierarchyisavailableforandcompatiblewithallversionsofWindows.ThecodeyoucreateinMFCisextremelyportable.ThesetutorialsintroducethefundamentalconceptsandvocabularybehindMFCandeventdrivenprogramming.Inthistutorialyouwillenter,compile,andrunasimpleMFCprogramusingVisualC+.Tutotial2providesadetailedexplanationofthecodeusedinTutorial1.Tutorial3discussesMFCcontrolsandtheircustomization.Tutorial4coversmessagemaps,whichletyouhandleeventsinMFC.WhatistheMicrosoftFoundationsClassLibrary?LetssayyouwanttocreateaWindowsapplication.Youmight,forexample,needtocreateaspecializedtextordrawingeditor,oraprogramthatfindsfilesonalargeharddisk,oranapplicationthatletsauservisualizetheinterrelationshipsinabigdataset.Wheredoyoubegin?Agoodstartingplaceisthedesignoftheuserinterface.First,decidewhattheusershouldbeabletodowiththeprogramandthenpickasetofuserinterfaceobjectsaccordingly.TheWindowsuserinterfacehasanumberofstandardcontrols,suchasbuttons,menus,scrollbars,andlists,thatarealreadyfamiliartoWindowsusers.Withthisinmind,theprogrammermustchooseasetofcontrolsanddecidehowtheyshouldbearrangedonscreen.Atime-honoredprocedureistomakearoughsketchoftheproposeduserinterface(bytraditiononanapkinorthebackofanenvelope)andplaywiththeelementsuntiltheyfeelright.Forsmallprojects,orfortheearlyprototypingphaseofalargerproject,thisissufficient.1Thenextstepistoimplementthecode.WhencreatingaprogramforanyWindowsplatform,theprogrammerhastwochoices:CorC+.WithC,theprogrammercodesattheleveloftheWindowsApplicationProgramInterface(API).ThisinterfaceconsistsofacollectionofhundredsofCfunctionsdescribedintheWindowsAPIReferencebooks.ForWindowsNT,theAPIistypicallyreferredtoastheWin32API,todistinguishitfromtheoriginal16-bitAPIoflower-levelWindowsproductslikeWindows3.1.MicrosoftalsoprovidesaC+librarythatsitsontopofanyoftheWindowsAPIsandmakestheprogrammersjobeasier.CalledtheMicrosoftFoundationClasslibrary(MFC),thislibrarysprimaryadvantageisefficiency.ItgreatlyreducestheamountofcodethatmustbewrittentocreateaWindowsprogram.ItalsoprovidesalltheadvantagesnormallyfoundinC+programming,suchasinheritanceandencapsulation.MFCisportable,sothat,forexample,codecreatedunderWindows3.1canmovetoWindowsNTorWindows95veryeasily.MFCisthereforethepreferredmethodfordevelopingWindowsapplicationsandwillbeusedthroughoutthesetutorials.WhenyouuseMFC,youwritecodethatcreatesthenecessaryuserinterfacecontrolsandcustomizestheirappearance.Youalsowritecodethatrespondswhentheusermanipulatesthesecontrols.Forexample,iftheuserclicksabutton,youwanttohavecodeinplacethatrespondsappropriately.Itisthissortofevent-handlingcodethatwillformthebulkofanyapplication.Oncetheapplicationrespondscorrectlytoalloftheavailablecontrols,itisfinished.YoucanseefromthisdiscussionthatthecreationofaWindowsprogramisastraightforwardprocesswhenusingMFC.Thegoalofthesetutorialsistofillinthedetailsandtoshowthetechniquesyoucanusetocreateprofessionalapplicationsasquicklyaspossible.TheVisualC+applicationdevelopmentenvironmentisspecificallytunedtoMFC,sobylearningMFCandVisualC+togetheryoucansignificantlyincreaseyourpowerasanapplicationdeveloper.WindowsVocabularyThevocabularyusedtotalkaboutuserinterfacefeaturesandsoftwaredevelopmentinWindowsisbasicbutunique.Herewereviewafewdefinitionstomakediscussioneasierforthosewhoarenewtotheenvironment.Windowsapplicationsuseseveralstandardusercontrols:StatictextlabelsPushbuttons2ListboxesComboboxes(amoreadvancedformoflist)RadioboxesCheckboxesEditabletextareas(singleandmulti-line)ScrollbarsYoucancreatethesecontrolseitherincodeorthrougharesourceeditorthatcancreatedialogsandthecontrolsinsideofthem.Inthissetoftutorialswewillexaminehowtocreatethemincode.SeethetutorialsontheAppWizardandClassWizardforanintroductiontotheresourceeditorfordialogs.Windowssupportsseveraltypesofapplicationwindows.Atypicalapplicationwillliveinsideaframewindow.Aframewindowisafullyfeaturedmainwindowthattheusercanre-size,minimize,maximizetofillthescreen,andsoon.Windowsalsosupportstwotypesofdialogboxes:modalandmodeless.Amodaldialogbox,onceonthescreen,blocksinputtotherestoftheapplicationuntilitisanswered.Amodelessdialogboxcanappearatthesametimeastheapplicationandseemstofloataboveittokeepfrombeingoverlaid.MostsimpleWindowsapplicationsuseaSingleDocumentInterface,orSDI,frame.TheClock,PIFeditor,andNotepadareexamplesofSDIapplications.WindowsalsoprovidesanorganizingschemecalledtheMultipleDocumentInterface,orMDIformorecomplicatedapplications.TheMDIsystemallowstheusertoviewmultipledocumentsatthesametimewithinasingleinstanceofanapplication.Forexample,atexteditormightallowtheusertoopenmultiplefilessimultaneously.WhenimplementedwithMDI,theapplicationpresentsalargeapplicationwindowthatcanholdmultiplesub-windows,eachcontainingadocument.Thesinglemainmenuisheldbythemainapplicationwindowanditappliestothetop-mostwindowheldwithintheMDIframe.IndividualwindowscanbeiconifiedorexpandedasdesiredwithintheMDIframe,ortheentireMDIframecanbeminimizedintoasingleicononthedesktop.TheMDIinterfacegivestheimpressionofaseconddesktopoutonthedesktop,anditgoesalongwaytowardsorganizingandremovingwindowclutter.Eachapplicationthatyoucreatewilluseitsownuniquesetofcontrols,itsownmenustructure,anditsowndialogboxes.Agreatdealoftheeffortthatgoesintocreatinganygoodapplicationinterfaceliesinthechoiceandorganizationoftheseinterfaceobjects.VisualC+,alongwithitsresourceeditors,makesthecreationandcustomizationoftheseinterfaceobjectsextremelyeasy.3Event-drivenSoftwareandVocabularyAllwindow-basedGUIscontainthesamebasicelementsandalloperateinthesameway.Onscreentheuserseesagroupofwindows,eachofwhichcontainscontrols,icons,objectsandsuchthataremanipulatedwiththemouseorthekeyboard.Theinterfaceobjectsseenbytheuserarethesamefromsystemtosystem:pushbuttons,scrollbars,icons,dialogboxes,pulldownmenus,etc.Theseinterfaceobjectsallworkthesameway,althoughsomehaveminordifferencesintheirlookandfeel.Forexample,scrollbarslookslightlydifferentasyoumovefromWindowstotheMactoMotif,buttheyalldothesamething.Fromaprogrammersstandpoint,thesystemsareallsimilarinconcept,althoughtheydifferradicallyintheirspecifics.TocreateaGUIprogram,theprogrammerfirstputsalloftheneededuserinterfacecontrolsintoawindow.Forexample,iftheprogrammeristryingtocreateasimpleprogramsuchasaFahrenheittoCelsiusconverter,thentheprogrammerselectsuserinterfaceobjectsappropriatetothetaskanddisplaysthemonscreen.Inthisexample,theprogrammermightlettheuserenteratemperatureinaneditabletextarea,displaytheconvertedtemperatureinanotherun-editabletextarea,andlettheuserexittheprogrambyclickingonapush-buttonlabeledquit.Astheusermanipulatestheapplicationscontrols,theprogrammustrespondappropriately.Theresponsesaredeterminedbytheusersactionsonthedifferentcontrolsusingthemouseandthekeyboard.Eachuserinterfaceobjectonthescreenwillrespondtoeventsdifferently.Forexample,iftheuserclickstheQuitbutton,thebuttonmustupdatethescreenappropriately,highlightingitselfasnecessary.Thentheprogrammustrespondbyquitting.Normallythebuttonmanagesitsappearanceitself,andtheprograminsomewayreceivesamessagefromthebuttonthatsays,Thequitbuttonwaspressed.Dosomethingaboutit.Theprogramrespondsbyexiting.Windowsfollowsthissamegeneralpattern.Inatypicalapplicationyouwillcreateamainwindowandplaceinsideitdifferentuserinterfacecontrols.Thesecontrolsareoftenreferredtoaschildwindows-eachcontrolislikeasmallerandmorespecializedsub-windowinsidethemainapplicationwindow.Astheapplicationprogrammer,youmanipulatethecontrolsbysendingmessagesviafunctioncalls,andtheyrespondtouseractionsbysendingmessagesbacktoyourcode.Ifyouhaveneverdoneanyevent-drivenprogramming,thenallofthismayseemforeigntoyou.However,theevent-drivenstyleofprogrammingiseasytounderstand.Theexactdetailsdependonthesystemandthelevelatwhichyouareinterfacingwithit,butthe4basicconceptsaresimilar.Inanevent-driveninterface,theapplicationpaintsseveral(ormany)userinterfaceobjectssuchasbuttons,textareas,andmenusontothescreen.Nowtheapplicationwaits-typicallyinapieceofcodecalledaneventloop-fortheusertodosomething.Theusercandoanythingtoanyoftheobjectsonscreenusingeitherthemouseorthekeyboard.Theusermightclickoneofthebuttons,forexample.Themouseclickiscalledanevent.Eventdrivensystemsdefineeventsforuseractionssuchasmouseclicksandkeystrokes,aswellasforsystemactivitiessuchasscreenupdating.Atthelowestlevelofabstraction,youhavetorespondtoeacheventinafairamountofdetail.ThisisthecasewhenyouarewritingnormalCcodedirectlytotheAPI.Insuchascenario,youreceivethemouse-clickeventinsomesortofstructure.Codeinyoureventlooplooksatdifferentfieldsinthestructure,determineswhichuserinterfaceobjectwasaffected,perhapshighlightstheobjectinsomewaytogivetheuservisualfeedback,andthenperformstheappropriateactionforthatobjectandevent.Whentherearemanyobjectsonthescreentheapplicationbecomesverylarge.Itcantakequiteabitofcodesimplytofigureoutwhichobjectwasclickedandwhattodoaboutit.Fortunately,youcanworkatamuchhigherlevelofabstraction.InMFC,almostalltheselow-levelimplementationdetailsarehandledforyou.Ifyouwanttoplaceauserinterfaceobjectonthescreen,youcreateitwithtwolinesofcode.Iftheuserclicksonabutton,thebuttondoeseverythingneededtoupdateitsappearanceonthescreenandthencallsapre-arrangedfunctioninyourprogram.Thisfunctioncontainsthecodethatimplementstheappropriateactionforthebutton.MFChandlesallthedetailsforyou:Youcreatethebuttonandtellitaboutaspecifichandlerfunction,anditcallsyourfunctionwhentheuserpressesit.Tutorial4showsyouhowtohandleeventsusingmessagemapsAnExampleOneofthebestwaystobeginunderstandingthestructureandstyleofatypicalMFCprogramistoenter,compile,andrunasmallexample.Thelistingbelowcontainsasimplehelloworldprogram.Ifthisisthefirsttimeyouveseenthissortofprogram,itprobablywillnotmakealotofsenseinitially.Dontworryaboutthat.Wewillexaminethecodeindetailinthenexttutorial.Fornow,thegoalistousetheVisualC+environmenttocreate,compileandexecutethissimpleprogram./hello.cpp#include/Declaretheapplicationclass5classCHelloApp:publicCWinApppublic:virtualBOOLInitInstance();/CreateaninstanceoftheapplicationclassCHelloAppHelloApp;/DeclarethemainwindowclassclassCHelloWindow:publicCFrameWndCStatic*cs;public:CHelloWindow();/TheInitInstancefunctioniscalledeach/timetheapplicationfirstexecutes.BOOLCHelloApp:InitInstance()m_pMainWnd=newCHelloWindow();m_pMainWnd-ShowWindow(m_nCmdShow);m_pMainWnd-UpdateWindow();returnTRUE;/TheconstructorforthewindowclassCHelloWindow:CHelloWindow()/CreatethewindowitselfCreate(NULL,HelloWorld!,WS_OVERLAPPEDWINDOW,CRect(0,0,200,200);/Createastaticlabelcs=newCStatic();6cs-Create(helloworld,WS_CHILD|WS_VISIBLE|SS_CENTER,CRect(50,80,150,150),this);Thissmallprogramdoesthreethings.First,itcreatesanapplicationobject.EveryMFCprogramyouwritewillhaveasingleapplicationobjectthathandlestheinitializationdetailsofMFCandWindows.Next,theapplicationcreatesasinglewindowonthescreentoactasthemainapplicationwindow.Finally,insidethatwindowtheapplicationcreatesasinglestatictextlabelcontainingthewordshelloworld.Wewilllookatthisprogramindetailinthenexttutorialtogainacompleteunderstandingofitsstructure.Thestepsnecessarytoenterandcompilethisprogramarestraightforward.IfyouhavenotyetinstalledVisualC+onyourmachine,dosonow.Youwillhavetheoptionofcreatingstandardandcustominstallations.Forthepurposesofthesetutorialsastandardinstallationissuitableandafteransweringtwoorthreesimplequestionstherestoftheinstallationisquickandpainless.StartVC+bydoubleclickingonitsiconintheVisualC+groupoftheProgramManager.Ifyouhavejustinstalledtheproduct,youwillseeanemptywindowwithamenubar.IfVC+hasbeenusedbeforeonthismachine,itispossibleforittocomeupinseveraldifferentstatesbecauseVC+remembersandautomaticallyreopenstheprojectandfilesinusethelasttimeitexited.Whatwewantrightnowisastatewhereithasnoprojectorcodeloaded.Iftheprogramstartswithadialogthatsaysitwasunabletofindacertainfile,clearthedialogbyclickingtheNobutton.GototheWindowmenuandselecttheCloseAlloptionifitisavailable.GototheFilemenuandselecttheCloseoptionifitisavailabletocloseanyremainingwindows.Nowyouareattheproperstartingpoint.Ifyouhavejustinstalledthepackage,youwillseeawindowthatlookssomethinglikethis:7Thisscreencanberatherintimidatingthefirsttimeyouseeit.Toeliminatesomeoftheintimidation,clickonthelowerofthetwoxbuttons()thatyouseeintheupperrighthandcornerofthescreenifitisavailable.ThisactionwillletyouclosetheInfoViewerTopicwindow.IfyouwanttogetridoftheInfoViewertoolbaraswell,youcandragitsoitdockssomewherealongthesideofthewindow,orcloseitandlatergetitbackbychoosingtheCustomizeoptionintheToolsmenu.Whatyouseenowisnormal.Alongthetopisthemenubarandseveraltoolbars.Alongtheleftsideareallofthetopicsavailablefromtheon-linebookcollection(youmightwanttoexplorebydoubleclickingonseveraloftheitemsyouseethere-thecollectionofinformationfoundintheon-linebooksisgigantic).Alongthebottomisastatuswindowwherevariousmessageswillbedisplayed.Nowwhat?Whatyouwouldliketodoistypeintheaboveprogram,compileitandrunit.Beforeyoustart,switchtotheFileManager(ortheMS-DOSprompt)andmakesureyourdrivehasatleastfivemegabytesoffreespaceavailable.Thentakethefollowingsteps.CreatingaProjectandCompilingtheCodeInordertocompileanycodeinVisualC+,youhavetocreateaproject.Withaverysmallprogramlikethistheprojectseemslikeoverkill,butinanyrealprogramtheprojectconceptisquiteuseful.Aprojectholdsthreedifferenttypesofinformation:Itremembersallofthesourcecodefilesthatcombinetogethertocreateoneexecutable.Inthissimpleexample,thefileHELLO.CPPwillbetheonlysourcefile,butinlargerapplicationsyouoftenbreakthecodeupintoseveraldifferentfilestomakeiteasierto8understand(andalsotomakeitpossibleforseveralpeopletoworkonitsimultaneously).Theprojectmaintainsalistofthedifferentsourcefilesandcompilesallofthemasnecessaryeachtimeyouwanttocreateanewexecutable.Itrememberscompilerandlinkeroptionsparticulartothisspecificapplication.Forexample,itrememberswhichlibrariestolinkintotheexecutable,whetherornotyouwanttousepre-compiledheaders,andsoon.Itrememberswhattypeofprojectyouwishtobuild:aconsoleapplication,awindowsapplication,etc.Ifyouarefamiliarwithmakefiles,thenitiseasytothinkofaprojectasamachine-generatedmakefilethathasaveryeasy-to-understanduserinterfacetomanipulateit.FornowwewillcreateaverysimpleprojectfileanduseittocompileHELLO.CPP.TocreateanewprojectforHELLO.CPP,choosetheNewoptionintheFilemenu.UndertheProjectstab,highlightWin32Application.IntheLocationfieldtypeanappropriatepathnameorclicktheBrowsebutton.Typethewordhelloinfortheprojectname,andyouwillseethatwordechoedintheLocationfieldaswell.ClicktheOKbutton.Inthenextwindow,usethedefaultselectionAnemptyproject,clickFinish,thenclickOKoncemoreinthenextwindow.NoticethereisanoptionforthetypicalHelloWorldapplication,howeveritskipsafewimportantstepsyouareabouttotake.VisualC+willcreateanewsubdirectorynamedHELLOandplacetheprojectfilesnamedHELLO.OPT,HELLO.NCB,HELLO.DSP,andHELLO.DSWinthatdirectory.Ifyouquitandlaterwanttoreopentheproject,double-clickonHELLO.DSW.Theareaalongtheleftsideofthescreenwillnowchangesothatthreetabsareavailable.TheInfoViewtabisstillthere,butthereisnowalsoaClassViewandaFileViewtab.TheClassViewtabwillshowyoualistofalloftheclassesinyourapplicationandtheFileViewtabgivesyoualistofallofthefilesintheproject.Nowitistimetotypeinthecodefortheprogram.IntheFilemenuselecttheNewoptiontocreateaneweditorwindow.Inthedialogthatappears,makesuretheFilestabisactiveandrequestaC+SourceFile.MakesuretheAddtoProjectoptionischeckedforProjecthello,andenterhelloforFilename.VisualC+comeswithitsownintelligentC+editor,andyouwilluseittoentertheprogramshownabove.Type(copy/paste)thecodeinthelistingintotheeditorwindow.Youwillfindthattheeditorautomaticallycolorsdifferentpiecesoftextsuchascomments,keywords,stringliterals,andsoon.Ifyouwanttochangethecolorsorturnthecoloringoff,gototheOptionsoptionintheToolsmenu,choose9theFormattabandselecttheSourceWindowsoptionfromthelefthandlist.Ifthereissomeaspectoftheeditorthatdispleasesyou,youmaybeabletochangeitusingtheEditortaboftheOptionsdialog.Afteryouhavefinishedenteringthecode,savethefilebyselectingtheSaveoptionintheFilemenu.SaveittoafilenamedHELLO.CPPinthenewdirectoryVisualC+created.Intheareaontheleftsideofthescreen,clicktheFileViewtabandexpandthetreeontheiconlabeledhellofiles,thenexpandthetreeonthefoldericonlabeledSourceFiles.YouwillseethefilenamedHELLO.CPP.ClickontheClassViewtabandexpandthehelloclassestreeandyouwillseetheclassesintheapplication.YoucanremoveafilefromaprojectatanytimebygoingtotheFileView,clickingthefile,andpressingthedeletebutton.Finally,youmustnowtelltheprojecttousetheMFClibrary.Ifyouomitthissteptheprojectwillnotlinkproperly,andtheerrormessagesthatthelinkerproduceswillnothelponebit.ChoosetheSettingsoptionintheProjectmenu.MakesurethattheGeneraltabisselectedinthetabatthetopofthedialogthatappears.IntheMicrosoftFoundationClassescombobox,choosethethirdoption:UseMFCinaSharedDLL.Thenclosethedialog.Havingcreatedtheprojectfileandadjustedthesettings,youarereadytocompiletheHELLO.CPPprogram.IntheBuildmenuyouwillfindthreedifferentcompileoptions:CompileHELLO.CPP(onlyavailableifthetextwindowforHELLO.CPPhasfocus)BuildHELLO.EXERebuildAllThefirstoptionsimplycompilesthesourcefilelistedandformstheobjectfileforit.Thisoptiondoesnotperformalink,soitisusefulonlyforquicklycompilingafiletocheckforerrors.Thesecondoptioncompilesallofthesourcefilesintheprojectthathavebeenmodifiedsincethelastbuild,andthenlinksthemtoformanexecutable.Thethirdoptionrecompilesallofthesourcefiles

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论