華東交大印度外教課程Single-Document-ppt_第1頁(yè)
華東交大印度外教課程Single-Document-ppt_第2頁(yè)
華東交大印度外教課程Single-Document-ppt_第3頁(yè)
華東交大印度外教課程Single-Document-ppt_第4頁(yè)
華東交大印度外教課程Single-Document-ppt_第5頁(yè)
已閱讀5頁(yè),還剩67頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

CreatingSingleDocument

InterfaceApplications

SDIapplicationisadocument-centricapplicationthatcanonlyworkwithonedocumentatatimeExamples:-SDIapplicationsNotepad,WordPad,andPaintAlloftheseapplicationscandoonlyonetypeoftaskandcanonlyworkononetaskatatimeMSWordallowsustoworkonnumerousdocumentsatthesametimeSummaryofthisclassTheDocument/ViewarchitecturethatVisualC++usesforcreatingSDIapplicationsHowtocreateanSDIapplicationshellHowtoseparateyourdatafromthevisualrepresentationofthedataHowtoencapsulateyourdatainitsownC++classHowtocreateinteractionbetweenthedataandthemenusTheDocument/ViewArchitectureWhenyoucreateanSDIapplication,moreclassesarecreatedforanSDIapplicationthanforadialog-styleapplication.EachoftheseclassesservesaspecificpurposeinhowSDIapplicationsoperateFourspecificclassesmakeupanSDIapplication

(1)TheCWinApp-derivedclass(2)TheCFrameView-derivedclass(3)TheCDocument-derivedclass(4)TheCView-derivedclassCWinAppclasscreatesalltheothercomponentsintheapplicationreceivesalltheeventmessagesandthenpassesthemessagestotheCFrameViewand

CViewclassesCFrameView

class[WindowFrame]holdsthemenu,toolbar,scrollbars,andanyothervisibleobjectsattachedtotheframe.determineshowmuchofthedocumentisvisibleatanytimeCDocumentclassWherethedatastructuresnecessarytohouseandmanipulatethedatathatmakesupyourdocumentarebuilt.Responsibleforsavingandretrievingthedocumentdatafromfiles.ReceivesinputfromtheCViewclassandpassesdisplayinformationtotheCViewclass.

CViewclassdisplaysthevisualrepresentationofyourdocumentfortheuser.passesinputinformationtotheCDocumentclassandreceivesdisplayinformationfromtheCDocumentclassTHECViewDESCENDENTCLASSESCEditView

:Providesthefunctionalityofaeditboxcontrol.Canbeusedtoimplementsimpletext-editorfunctionality.CFormView

:Thebaseclassforviewscontainingcontrols.Canbeusedtoprovideform-baseddocumentsinapplications.Contd…CHtmlView:ProvidesthefunctionalityofaWebbrowser.ThisviewdirectlyhandlestheURLnavigation,hyperlinking,andsoon.

Maintainsahistorylistforbrowsingforwardandback.Contd…CListView

:Provideslist-controlfunctionalityintheDocument/Viewarchitecture.CRichEditView:(a)Providescharacterandparagraphformattingfunctionality.(b)Canbeusedtoimplementaword-processorapplicationContd…CScrollView:ProvidesscrollingcapabilitiestoaCViewclass.CTreeView:Providestree-controlfunctionalityintheDocument/Viewarchitecture.CreatinganSDIApplicationStep1:CreateanewAppWizardproject.NametheprojectDay10Step2:InthefirststepoftheAppWizard,selectSingleDocument.3.UsethedefaultvaluesonthesecondstepoftheAppWizard4.OnthethirdstepoftheAppWizard,uncheckthesupportforActiveXControls.Step5:OnthefourthstepoftheAppWizard,leaveallthedefaultvalues.ClicktheAdvancedbutton.Step6:IntheAdvancedOptionsdialog,enterathree-letterfileextensionforthefilesthatyourapplicationwillgenerate(forexample,dhcordvp).Step7:UsethedefaultsettingsonthefifthstepoftheAppWizard.Step8:OnthesixthandfinalAppWizardstep,youcanchoosethebaseclassonwhichyourviewclasswillbebased.LeavethebaseclassasCViewandclickFinish.TheAppWizardwillgeneratetheapplicationshellCreatingaLineClassMicrosoftFoundationClasses(MFC)doesnothavealineobjectclass,althoughitdoeshaveapointobjectclass(CPoint).Createyourownlineclassbyfollowingthesesteps:

Step1:IntheClassViewtaboftheworkspacepane,selectthetop-levelobjectinthetree.Right-clickthemouseandselectNewClassfromthepop-upmenu.Contd..Step2:IntheNewClassdialog,selectGenericClassfortheclasstype.EnterCLinefortheclassnameandclickinthefirstlineintheBaseClasslistbox.EnterCObjectasthebaseclass,leavingtheclassaccessaspublic,asinFigure(1)

TheNewClassWizardStep3:WhenyouclicktheOKbuttontoaddtheCLineclass,youmaybetoldthattheClassWizardcannotfindtheappropriateheaderfileforinheritingtheCLineclassfromtheCObjectclass,asinFigure(2).ClickontheOKbutton.

Warningabout

includingthebase

classdefinition.ConstructingtheCLineClassNOTE:(1)CLineclassneedstoholdonlytwodataelements,thetwoendpointsofthelinethatitrepresents.(2)addthosetwodataelementsandaddaclassconstructorthatsetsbothvalueswhencreatingtheclassinstanceFollowthesesteps:

1.IntheClassViewtaboftheworkspacepane,selecttheCLineclass.2.Right-clicktheCLineclassandchooseAddMemberVariablefromthepop-upmenu.3.Enter

CPointasthevariabletypeandm_ptFromasthevariablename,andmarktheaccessasPrivateandclickO.K.Contd…4.Repeatsteps2and3,namingthisvariablem_ptTo.5.Right-clicktheCLineclassandchooseAddMemberFunctionfromthepop-upmenu.6.Leavethefunctiontypeblank,andenterCLine(CPoint

ptFrom,CPoint

ptTo)forthefunctiondeclarationandClickOKTHECLineCONSTRUCTOR7.Editthenewfunctionandaddthecode.CLine::CLine(CPoint

ptFrom,CPoint

ptTo){

m_ptFrom=ptFrom;

m_ptTo=ptTo;}Inthisobjectconstructor,youareinitializingthefromandtopointswiththepointsthatwerepassedintotheconstructor.DrawingtheCLine

ClassNOTE:

Tofollowcorrectobject-orienteddesign,yourCLineclassshouldbeabletodrawitselfsothatwhentheviewclassneedstorenderthelinefortheuser,itcanjustpassamessagetothelineobject,tellingittodrawitself.Toaddthisfunctionality,followthesesteps:THECLineDrawFUNCTION1.AddanewfunctiontotheCLineclassbyselectingAddMemberFunctionfromthepop-upmenu.2.SpecifythefunctiontypeasvoidandthefunctiondeclarationasDraw(CDC*pDC).3.AddthecodeinListingshowntotheDrawfunctionyoujustadded.THECLineDrawFUNCTIONvoidCLine::Draw(CDC*pDC){//Drawtheline

pDC->MoveTo(m_ptFrom);

pDC->LineTo(m_ptTo);}

It’sasimplefunctionthatmovestothefirstpointonthedevicecontextandthendrawsalinetothesecondpointonthedevicecontext.

ImplementingtheDocumentFunctionalityStoretheCLineobjectsonthedocumentobjectinasimpledynamicarrayToholdthisarray,youcanaddaCObArraymembervariabletothedocumentclass.TheCObArrayclassisanobjectarrayclassthatdynamicallysizesitselftoaccommodateTheCObArrayclassanobjectarrayclassthatdynamicallysizesitselftoaccommodatethenumberofitemsplacedinit.ItcanholdanyobjectsthataredescendedfromtheCObjectclass,anditislimitedinsizeonlybytheamountofmemoryinthesystem.OtherdynamicarrayclassesinMFCincludeCStringArray,CByteArray,CWordArray,CDWordArray,andCPtrArrayTheseclassesdifferbythetypeofobjectstheycanhold.AddtheCObArraytoCDay10DocClass,usingtheAddMemberVariableWizardandnameitasm_oaLines.AddingLinesThefirstfunctionalitytobeaddedtothedocumentclassistheabilitytoaddnewlines.Thisshouldbeasimpleprocessofgettingthefromandtopoints,creatinganewlineobject,andthenaddingittotheobjectarray.Toimplementthisfunction:AddanewmemberfunctiontotheCDay10Docclass,specifyingthetypeasCLine*andthedeclarationasAddLine(CPoint

ptFrom,CPoint

ptTo)withpublicaccessEditthefunction,addingthecodeshown:THECDay10DocAddLineFUNCTION.CLine*CDay10Doc::AddLine(CPointptFrom,CPoint

ptTo){//CreateanewCLineobject

CLine*pLine=newCLine(ptFrom,ptTo);try{//Addthenewlinetotheobjectarray

m_oaLines.Add(pLine);//Markthedocumentasdirty

SetModifiedFlag();}Contd…

//Didwerunintoamemoryexception?

catch(CMemoryException*perr){//Displayamessagefortheuser,givinghimorher/hebadnews

AfxMessageBox(“Outofmemory”,B_ICONSTOP|MB_OK);

Contd…//Didwecreatealineobject?

if(pLine){//Deleteit

deletepLine;

pLine=NULL;}//Deletetheexceptionobject

perr->Delete();}

returnpLine;}ExplanationforthecodecreatesanewCLineinstance,passingthefromandtopointsasconstructorarguments.Withinthetrysection,thenewCLineinstanceisaddedtothearrayoflineobjects.ExplanationforthecodeNext,theSetModifiedFlagfunctioniscalled,whichmarksthedocumentas“dirty”(unsaved)sothatifyouclosetheapplicationoropenanotherfilewithoutsavingthecurrentdrawingfirst,theapplicationpromptsyoutosavethecurrentdrawing(withthefamiliarYes,No,Cancelmessagebox).ExplanationforthecodeInthecatchsection,theisinformedthatthesystemisoutofmemoryandthencleanupbydeletingtheCLineobjectandtheexceptionobject.Finally,attheendofthefunction,youCLineobjectisreturnedtothecallingroutine.Thisenablestheviewobjecttoletthelineobjectdrawitself.GettingtheLineCountThenextfunctiontobeaddedtothedocumentclassisafunctiontoreturnthenumberoflines

inthedocument.Thisfunctionalityisnecessarybecausetheviewobjectneedstoloopthroughthearrayoflines,askingeachlineobjecttodrawitself.Theviewobjectwillneedtobeabletodeterminethetotalnumberoflinesinthedocumentandretrieveanyspecificlinefromthedocument.THECDay10DocGetLineCountFUNCTION.intCDay10Doc::GetLineCount(){//Returnthearraycount

returnm_oaLines.GetSize();}RetrievingaSpecificLineFinally,afunctionisaddedtoreturnaspecificlinefromthedocument.Toimplementthisfunction,addanewmemberfunctiontotheCDay10Docclass,specifyingthetypeasCLine*andthedeclarationasGetLine(int

nIndex)withpublicaccess.THECDay10DocGetLineFUNCTION.CLine*CDay10Doc::GetLine(intnIndex){//Returnapointertothelineobject//atthespecifiedpointintheobjectarray

return(CLine*)m_oaLines[nIndex];}ShowingtheUserneedtoaddthefunctionalitytotheviewobjecttoreadtheuser’sdrawinginputandtodrawtheimage.ThesecondpartofthefunctionalitythatyouneedtoimplementisdrawingtheimageneedtoaddamembervariabletotheCDay10ViewclasstomaintainthepreviousmousepointContd…AddamembervariabletotheCDay10Viewclassthroughtheworkspacepane,specifyingthetypeasCPoint,thenameasm_ptPrevPos,andtheaccessasprivate.

AddingtheMouseEventsToaddthemouseeventstocapturetheuser’sdrawingefforts,opentheClassWizardandaddfunctionstotheCDay10ViewclassfortheM_LBUTTONDOWN,WM_LBUTTONUP,and

WM_MOUSEMOVEeventmessages.THECDay10ViewMOUSEFUNCTIONS

M_LBUTTONDOWN

voidCDay10View::OnLButtonDown(UINTnFlags,CPointpoint){//Capturethemouse,sonootherapplicationcangrabitifthemouseleavesthewindowarea

SetCapture();//Savethepoint

m_ptPrevPos=point;

//MYCODEENDSHERE

CView::OnLButtonDown(nFlags,point);}WM_LBUTTONUPvoidCDay10View::OnLButtonUp(UINTnFlags,CPointpoint){//Havewecapturedthemouse?if(GetCapture()==this)//Ifso,releaseitsootherapplicationscanhaveit

ReleaseCapture();//MYCODEENDSHERE

CView::OnLButtonUp(nFlags,point);}

WM_MOUSEMOVEvoidCDay10View::OnMouseMove(UINTnFlags,CPointpoint)if((nFlags&MK_LBUTTON)==MK_LBUTTON){//Havewecapturedthemouse?

if(GetCapture()==this){//GettheDeviceContext

CClientDC

dc(this);

Codecontd..//Addthelinetothedocument

CLine*pLine=GetDocument()->AddLine(m_ptPrevPos,point);//Drawthecurrentstretchofline

pLine->Draw(&dc);//Savethecurrentpointasthepreviouspoint

m_ptPrevPos=point;}}CView::OnMouseMove(nFlags,point);}CodeexplanationIntheOnMouseMovefunction,afteryoucreateyourdevicecontext,youdoseveralthingsinasinglelineofcode.ThelineCLine*pLine=GetDocument()->AddLine(m_ptPrevPos,point);createsanewpointertoaCLineclassinstance.Contd…Next,itcallstheGetDocumentfunction,whichreturnsapointertothedocumentobject.Thispointerisusedtocallthedocumentclass’sAddLinefunction,passingthepreviousandcurrentpointsasarguments.ThereturnvaluefromtheAddLinefunctionisusedtoinitializetheCLineobjectpointer.DrawingthePaintingIntheviewclass,thefunctionOnDrawiscalledwhenevertheimagepresentedtotheuserneedstoberedrawn.LocatetheOnDrawfunctionintheCDay10ViewclassandaddthecodeinListingTHECDay10ViewOnDrawFUNCTION{CDay10Doc*pDoc=GetDocument();

ASSERT_VALID(pDoc);//TODO:adddrawcodefornativedatahere//Getthenumberoflinesinthedocument

int

liCount=pDoc->GetLineCount();

Contd…//Arethereanylinesinthedocument?if(liCount){

int

liPos;

CLine*lptLine;//Loopthroughthelinesinthedocumentfor(liPos=0;liPos<liCount;liPos++){//Getthefromandtopointforeachline

lptLine=pDoc->GetLine(liPos);//Drawtheline

lptLine->Draw(pDC);}}}Beforeyoucancompileandrunyourapplication,you’llneedtoincludetheheaderfilefortheClineclassinthesourcecodefileforthedocumentandviewclasses.Toaddthistoyourapplication,editbothofthesefiles(Day10Doc.cppandDay10View.cpp),addingtheLine.hfiletotheincludes,asshowninListingTHECDay10Docincludes.

#include“stdafx.h”#include“Day10.h”#include“MainFrm.h”#include“Line.h”#include“Day10Doc.h”CompileandRunyourApplicationSavingandLoadingtheDrawingIfyouusethemenusonyourapplication,itappearsthattheOpen,Save,andSaveAsmenuentriesontheFilemenuactivate,buttheydon’tseemtodoanything.Theprintingmenuentriesallwork,buttheentriesforsavingandloadingadrawingdon’t.DeletingtheCurrentDrawingOpentheClassWizardandaddafunctiononthe

DeleteContentseventmessage.Thiseventmessageisintendedforclearingthecurrentcontentsofthedocumentclass.Editthisnewfunction,addingthecodeinListingshownTHECDay10DocDeleteContentsFUNCTIONvoidCDay10Doc::DeleteContents(){//TODO:Addyourspecializedcodehereand/orcallthebaseclass//Getthenumberoflinesintheobjectarray

int

liCount=m_oaLines.GetSize();

int

liPos;//Arethereanyobjectsinthearray?Contd..if(liCount){//Loopthroughthearray,deletingeachobject

for(liPos=0;liPos<liCount;liPos++)

deletem_oaLines[liPos];//Resetthearray

m_oaLines.RemoveAll();}

CDocument::DeleteContents();}Thisfunctionloopsthroughtheobjectarray,

deletingeachlineobjectinthearray.Onceallthelinesaredeleted,thearrayisresetbycallingitsRemoveAllmethod.Ifyoucompileandrunyourapplication,you’llfindthatyoucanselectFile|New,andifyoudecidenottosaveyourcurrentdrawing,yourwindowiswipedclean.SavingandRestoringtheDrawingsavingandrestoringfiles:serializationfindtheSerializefunctionintheCDay10DocclassRemoveallthecontentsofthisfunction,andeditthefunctionsothatitlookslikeListingshowninthenextslide:THECDay10DocSerializeFUNCTIONvoidCDay10Doc::Serialize(CArchive&ar){//Passtheserializationontotheobjectarray

m_oaLines.Serialize(ar);}Thisfunctiontakesadvantageofthefunctionalityofthe

CObArrayclass.Thisobjectarraywillpas

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論