




版權(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ì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年1月專職安全生產(chǎn)管理人員綜合類C證練習(xí)題含參考答案
- 重難點(diǎn)解析人教版八年級(jí)上冊(cè)物理《聲現(xiàn)象》定向練習(xí)試卷(附答案詳解)
- 2025及未來(lái)5年中國(guó)九抽屜市場(chǎng)調(diào)查、數(shù)據(jù)監(jiān)測(cè)研究報(bào)告
- 2025及未來(lái)5年中國(guó)直流接觸器市場(chǎng)調(diào)查、數(shù)據(jù)監(jiān)測(cè)研究報(bào)告
- 2025及未來(lái)5年中國(guó)飲料貨架市場(chǎng)調(diào)查、數(shù)據(jù)監(jiān)測(cè)研究報(bào)告
- 2025及未來(lái)5年中國(guó)單桿市場(chǎng)調(diào)查、數(shù)據(jù)監(jiān)測(cè)研究報(bào)告
- 2025及未來(lái)5年中國(guó)荷蘭豆市場(chǎng)調(diào)查、數(shù)據(jù)監(jiān)測(cè)研究報(bào)告
- 考點(diǎn)解析-人教版八年級(jí)《力》專題練習(xí)試卷(含答案解析)
- 解析卷人教版八年級(jí)上冊(cè)物理《聲現(xiàn)象》定向訓(xùn)練試題(含解析)
- 廣安木紋硅鈣板施工方案(3篇)
- 變頻器基礎(chǔ)知識(shí)培訓(xùn)
- 函數(shù)零點(diǎn)問(wèn)題 課件-2025屆高三數(shù)學(xué)一輪復(fù)習(xí)
- 醫(yī)院培訓(xùn)課件:《腎病綜合征》
- 我愛(ài)你中國(guó) 女聲領(lǐng)唱與混聲四部合唱譜
- 智慧樹(shù)知到《星期音樂(lè)會(huì)(同濟(jì)大學(xué))》章節(jié)測(cè)試答案
- 穿脫隔離衣的流程及注意事項(xiàng)
- 《公寓運(yùn)營(yíng)方案》課件
- 鈣鈦礦太陽(yáng)能電池課件
- 關(guān)于違法違紀(jì)的思想?yún)R報(bào)
- 閩教版2023版3-6年級(jí)全8冊(cè)英語(yǔ)單詞表
- 成功的自媒體案例分享
評(píng)論
0/150
提交評(píng)論