220 likes | 343 Views
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
E N D
MFCWindowsProgramming: Document/ViewApproach Moredetailednotesat: http://dforeman.cs.binghamton.edu/~foreman/360/notes-html/class15.htm
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
�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
OtherClassesareStill Needed �StillneedtocreateCFrameWndand CWinAppclasses �Buttheirrolesarereduced Documents �Document –Containanyforms ofdataassociatedwith the application(puredata) –Notlimitedtotext –Couldbeanything •gamedata,graphicaldata,etc.
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
FrameWindow �Windowinwhichaviewofa documentisdisplayed �Adocumentcanhavemultiple viewsassociatedwithit –differentwaysoflookingatthe samedata �Butaviewhasonlyone documentassociatedwithit
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
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)
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();
Document/ViewPrograms �Almostalwayshaveatleastfourclassesderived from: – CFrameWnd – CDocument – CView – CWinApp �Usuallyputintoseparatedeclaration(.h)and implementation (.cpp) files �Becauseoftemplateanddynamiccreation,there’s lotsofinitialization �Couldbedonebyhand,butnobodydoesitthatway MicrosoftDeveloperStudio AppWizardandClassWizard Tools
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
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
SketchingRequirements �Ifleftmousebuttonisdown: –Eachtimemousemoves: •GetaDC •Createapenofdrawingcolor •SelectpenintoDC •Movetooldpoint •Drawalinetothenewpoint •Makecurrentpointtheoldpoint •SelectpenoutofDC Variables �BOOLEANm_butdn �CPointm_pt,m_ptold �COLORREFm_color �CDC*pDC
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
�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;
�RepeatprocessforWM_LBUTTONUP handler: –ScrolltoWM_LBUTTONUP –Click:“<Add>OnLButtonUp”, –EditCodeby adding: m_butdn=FALSE;
�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);
�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
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);
AnotherMethodofAddinga MenuItemCommandHandler –InClassViewSelectCSketchView –InPropertieswindowselectEvents(lightning bolticon) –Scrolldownto:ID_DRAWINGCOLOR_RED –Select“COMMAND” –Click “<Add>OnDrawingcolorRed”handler –Editcodebyadding: m_color=RGB(255,0,0);
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();
DestroyingtheWindow �JustneedtocallDestroyWindow() –DothisintheCMainFrameclass–usually inresponsetoa“Quit”menuitem