1 / 22

MF C Window s Programming: Document/View Approach Mor e detaile d note s at:

MF C Window s Programming: Document/View Approach Mor e detaile d note s at: http://dforeman.cs.binghamton.edu/~foreman/360/notes-html/class15.htm. MF C Window s Programming: App/Windo w Approach vs . Document/View Approach

rhys
Download Presentation

MF C Window s Programming: Document/View Approach Mor e detaile d note s at:

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MFCWindowsProgramming: Document/ViewApproach Moredetailednotesat: http://dforeman.cs.binghamton.edu/~foreman/360/notes-html/class15.htm

  2. MFCWindowsProgramming: App/WindowApproach vs. Document/View Approach AnApp/Windowapproachprogram createsapplicationandwindowobjects MirrorsWin32 APIprogramorganization Maindifference--MFCautomatesandmasks details… anddoesmanyothernecessarytasks But data&renderingofdataare intertwined Frequently,datamembersexistinwindowclass –ExampleinMSG2005.CPP:Outputstringdefinedin window-basedclass • Butoutputstringisdata • Reallyhasnothingtodowithwindowit’sbeingdisplayedin

  3. �Conceptuallydataisdifferentfrom renderingofdata �InanApp/Windowapproachprogram theyare mixedtogetherinsamewindow class �Frequentlyweneedtohavedifferentviews ofsamedata –(e.g.,displayingdatainawindoworonaprinter) �Soit’sagoodideatoseparatedataanddatapresentation Doc/ViewAchievesSeparationof DataandDataPresentation �EncapsulatesdatainaCDocumentclassobject �Encapsulatesdatadisplaymechanismand userinteractionwith itinaCViewclassobject �ClassesderivedfromCDocument –Shouldhandleanythingaffectinganapplication's data �ClassesderivedfromCView –Shouldhandledisplayofdataanduser interactionswiththatdisplay

  4. OtherClassesareStill Needed �StillneedtocreateCFrameWndand CWinAppclasses �Buttheirrolesarereduced Documents �Document –Containanyforms ofdataassociatedwith the application(puredata) –Notlimitedtotext –Couldbeanything •gamedata,graphicaldata,etc.

  5. DocumentInterfaces �SingleDocumentinterface(SDI)application –Programthatdealswithonedocumentatatime –AllourprogramstodatehavebeenSDIapps �MultipleDocumentInterface(MDI) application –Programorganizedtohandlemultipledocuments simultaneously –Morethanonedocumentcanbedisplayedina windowatthesametime –Example of anMDIapplication:MicrosoftExcel Views �Arenderingofadocument;a physicalrepresentationofthedata �Providesmechanismfordisplaying datastoredinadocument �Defineshowdataistobedisplayedin awindow �Defineshowtheusercaninteractwithit

  6. FrameWindow �Windowinwhichaviewofa documentisdisplayed �Adocumentcanhavemultiple viewsassociatedwithit –differentwaysoflookingatthe samedata �Butaviewhasonlyone documentassociatedwithit

  7. MFCTemplateClassObject �Handlescoordinationbetweendocuments,views,andframewindows �Ingeneral: –Applicationobjectcreatesatemplate... –whichcoordinatesdisplayofdocument'sdata… –in a view… –inside a frame window �i.e.,our CWinAppobjectcreatesaDocument TemplatewhichcreatesaCDocumentobjectand aCFrameWndobject –TheCFrameWndobjectcreatesaCViewobject –Whichdisplaysthedocumentdata Template/Document/View/Window

  8. Serialization �Providesforstorage/retrieval ofdocumentdata �Usuallyto/fromadiskfile �CDocumentclasshasserializationbuiltintoit –SoinDOCUMENT/VIEWapps, saving/storingdataisstraightforward DynamicCreation �InDoc/Viewapproach,objectsaredynamic �Doc/Viewprogramis run –Its frame window, document, and view are created dynamically –Often Doc/View objects are synthesized from file data • Theyneedtobecreatedatloadtime(runtime) –Toallowfordynamiccreation,usedynamic creationmacros • inclassesderivedfromCFrameWnd,CDocument,and CView)

  9. DynamicCreationMacros �DECLARE_DYNCREATE(class_name) –indeclaration(.hfile) �IMPLEMENT_DYNCREATE(class_name, parent_class_name) –(in .cpp file) �AfterIMPLEMENT_DYNCREATE()macroisinvoked: –Classisenabledfordynamiccreation –Nowatemplatecanbecreated SDIDoc/ViewCWinApp’sClass InitInstance() �Create document template and window: CSingleDocTemplate*pDocTemplate( IDR_MAINFRAME //ResourceID RUNTIME_CLASS(CPgmDoc) // the document RUNTIME_CLASS(CMainFrame)//mainSDIframewindow RUNTIME_CLASS(CPgmView)); //theview //RUNTIME_CLASS():amacroreturnspointerstoapp,doc,viewclasses //Willonlyworkafterdynamicdeclaration/creationmacrosareinvoked AddDocTemplate(pDocTemplate): //Addstemplateandcreateswindow �Finally,showwindowandupdateclientareaasusual: m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow();

  10. Document/ViewPrograms �Almostalwayshaveatleastfourclassesderived from: – CFrameWnd – CDocument – CView – CWinApp �Usuallyputintoseparatedeclaration(.h)and implementation (.cpp) files �Becauseoftemplateanddynamiccreation,there’s lotsofinitialization �Couldbedonebyhand,butnobodydoesitthatway MicrosoftDeveloperStudio AppWizardandClassWizard Tools

  11. AppWizard �ToolthatgeneratesaDoc/ViewMFCprogramframework automatically �Canbe builton andcustomizedby programmer �Fast,efficientwayofproducingWindowsApps �Performsrequiredinitializationautomatically �CreatesfunctionalCFrameWnd,CView,CDocument,CWinAppclasses �AfterAppWizarddoesit'sthing: –Applicationcanbebuiltandrun –Full-fledged window with all common menu items, tools,etc. ClassWizards �Facilitatemessagehandlinginaframework-basedMFCapplication �Toolsthatconnectresourcesanduser-generatedeventstoprogramresponsecode �WriteC++skeletonroutinestohandlemessages �Insertcodeintoappropriateplacesinprogram –Codethencanthenbecustomizedbyhand �Can beusedtocreatenewclassesorderiveclassesfromMFCbaseclasses –Addnewmembervariables/functionstoclasses �In.NETmany“classwizards”areavailablethroughPropertieswindow

  12. SKETCHApplication �ExampleofUsingAppWizardand ClassWizard �Usercanusemouseasadrawingpencil Leftmousebuttondown: –linesin windowfollowmousemotion �Leftmousebuttonup: –sketchingstops �Userclicks"Clear"menuitem –windowclientareaiserased �Sketchdata(points)won'tbesaved –Soleavedocument(CSketchDoc)class createdbyAppWizardalone �Basefunctionalityofapplication (CSketchApp) andframewindow(CMainFrame)classesareadequate –Leavethemalone �UseClassWizardtoaddsketchingtoCView class

  13. SketchingRequirements �Ifleftmousebuttonisdown: –Eachtimemousemoves: •GetaDC •Createapenofdrawingcolor •SelectpenintoDC •Movetooldpoint •Drawalinetothenewpoint •Makecurrentpointtheoldpoint •SelectpenoutofDC Variables �BOOLEANm_butdn �CPointm_pt,m_ptold �COLORREFm_color �CDC*pDC

  14. StepsinPreparingSKETCH �1.“File/New/Project” –ProjectType:“VisualC++Projects” –Template:“MFCApplication” –Entername:Sketch �2.In“WelcometoMFCApplicationWizard” –Applicationtype:“SingleDocument”Application –Takedefaultsforallotherscreens �3.BuildApplication-->Full-fledgedSDIAppwith emptywindowandno functionality �4.AddmembervariablestoCSketchView –Candomanuallyin.hfile –Easierto: • SelectClassViewpane • ClickonSketchViewclass –Notememberfunctions&variables • RightclickonCSketchViewclass –Choose“Add”/“Variable” –Launches“AddMemberVariableWizard” –VariableType:enterCPoint –Name:m_pt –Access:Public(default) –Noteafter“Finish”thatit’sbeenaddedtothe.hfile • Repeatforothervariables(oradddirectlyin.hfile): –CPoint m_ptold –bool m_butdn –COLORREF m_color –CDC* pDC

  15. �5.Addmessagehandlerfunctions: –SelectCSketchViewinClassView –Select“Messages”icon in Properties window • ResultsinalistofWM_messages –ScrolltoWM_LBUTTONDOWN&selectit –Add the handler by clicking on down arrow and “<Add>OnLButtonDown” • Notethatthefunctionisaddedintheeditwindowandthe cursorispositionedoverit: –After“TODO…”enterfollowingcode: m_butdn=TRUE; m_ptold=point;

  16. �RepeatprocessforWM_LBUTTONUP handler: –ScrolltoWM_LBUTTONUP –Click:“<Add>OnLButtonUp”, –EditCodeby adding: m_butdn=FALSE;

  17. �RepeatforWM_MOUSEMOVE –ScrolltoWM_MOUSEMOVE –Click:“<Add>OnMouseMove” –Editbyaddingcode: if(m_butdn) { pDC=GetDC(); m_pt=point; CPennewPen(PS_SOLID,1,m_color); CPen*pPenOld=pDC->SelectObject(&newPen); pDC->MoveTo(m_ptold); pDC->LineTo(m_pt); m_ptold=m_pt; pDC->SelectObject(pPenOld); } �6.Initializevariablesin CSketchViewconstructor –DoubleclickonCSketchViewconstructor •CSketchView(void)inClassView –After“TODO…”,Addcode: m_butdn=FALSE; m_pt=m_ptold=CPoint(0,0); m_color=RGB(0,0,0);

  18. �7.ChangingWindow’sProperties –Usewindow’sSetWindowXxxxx()functions •InCWinApp-derivedclassbeforewindowis shown and updated –Example:Changingthedefaultwindowtitle m_pMainWnd->SetWindowText( TEXT(“SketchingApplication”)); –TherearemanyotherSetWindowXxxxx() functionsthatcanbeusedtochangeother propertiesofthewindow �8.Buildandruntheapplication MenusandCommand Messages �Userclickson menuitem �WM_COMMANDmessageissent �ID_XXXidentifieswhichmenuitem(itsID) �Nopredefinedhandlers �Somessagemappingmacroisdifferent �ON_COMMAND(ID_XXX,OnXxx) –OnXxx()isthehandlerfunction –Mustbedeclaredin.hfileanddefinedin.cppfile

  19. AddingColorandClearMenu ItemstoSKETCHApp �ResourceView(sketch.rcfolder) –DoubleclickMenufolder –DoubleclickIDR_MAINFRAMEmenu –Add:“DrawingColor”popupmenuitemwithitems: •“Red”,ID_DRAWING_COLOR_RED(default) •“Blue”, ID_DRAWINGCOLOR_BLUE •“Green”, ID_DRAWINGCOLOR_GREEN •“Black”, ID_DRAWINGCOLOR_BLACK –Addanothermainmenuitem: •“ClearScreen”, ID_CLEARSCREEN •SetPopuppropertytoFalse AddMenuItemCommand HandlerFunction –Oneway:Use“EventHandlerWizard” –In“ResourceView”bring up menu editor –Right click on“Red”menuitem –Select“AddEventHandler”�“EventHandler Wizard” dialogbox •Classlist:CSketchView •Messagetype:COMMAND •Function handler name: accept default –OnDrawingcolorRed •Clickon“Addandedit” •After“TODO…”ineditorenterfollowingcode: m_color=RGB(255,0,0);

  20. AnotherMethodofAddinga MenuItemCommandHandler –InClassViewSelectCSketchView –InPropertieswindowselectEvents(lightning bolticon) –Scrolldownto:ID_DRAWINGCOLOR_RED –Select“COMMAND” –Click “<Add>OnDrawingcolorRed”handler –Editcodebyadding: m_color=RGB(255,0,0);

  21. RepeatforID_DRAWINGCOLOR_BLUE Code:m_color=RGB(0,0,255); RepeatforID_DRAWINGCOLOR_GREEN Code:m_color=RGB(0,255,0); RepeatforID_DRAWINGCOLOR_BLACK Code:m_color=RGB(0,0,0); RepeatforID_CLEAR Code:Invalidate();

  22. DestroyingtheWindow �JustneedtocallDestroyWindow() –DothisintheCMainFrameclass–usually inresponsetoa“Quit”menuitem

More Related