The SDI Application單文檔程序

在這裏將講述SDI程序中application object、the main frame window、the document、the view、the document template object以及the associate string and menu resources之間的關係。
 
The Windows Application Object
在CWinApp派生類的Implement文件中會有類似CMyApp theApp的語句。theApp是一個全局變量,它就是啓動MFC應用程序的機制所在。
以下是MFC應用程序啓動的摘要:
1、Windows把應用程序加載到內存;
2、構造全局變量theApp(所有全局變量在程序被載入內存時被構造);
3、Windows調用全局函數WinMain,它是MFC的一部分,等同於無窗口應用程序的main函數---主程序的入口;
4、WinMain尋找到CWinApp派生類的對象theApp;
5、WinMain爲theApp調用InitInstance函數,InitInstance函數可以被重載;
6、重載的InitInstance函數啓動加載document、顯示the main frame and view windows;
7、WinMain爲theApp啓動Run函數,Run函數負責分派window messages和command messages。
 
The Document Template Class
在CWinApp派生類的InitInstance中會有如下代碼:
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
    IDR_MAINFRAME,
    RUNTIME_CLASS(CStudentDoc),
    RUNTIME_CLASS(CMainFrame),       // main SDI frame window
    RUNTIME_CLASS(CStudentView));
AddDocTemplate(pDocTemplate);
這段代碼建立了the application class、the document class、the view window class、the main frame window四個類之間的聯繫。這時,application class的對象已經存在(theApp),但其他四個類的對象還沒有構造,MFC的動態創建機制就起到了作用。
一下兩個圖分別表示了以上四個類之間的關係、四個類的對象之間的關係:
鍥涗釜綾誨璞$殑鍏崇郴
 

Creating an Empty Document—The CWinApp::OnFileNew Function

當application class的InitInstance調用完AddDocTemplate以後,它將調用OnFileNew。
OnFileNew做如下事情:
1、構造Document對象,但不從硬盤中讀取數據;
2、構造the main frame對象和the main frame window,但不顯示它,它包括IDR_MAINFRAME、the toolbar、the status bar;
3、構造view對象和view窗口,但不顯示它;
4、建立the document、main frame、view對象之間的關係,這裏要藉助AddDocTemplate建立的類關係;
5、爲document對象調用虛函數CDocument::OnNewDocument,CDocument::OnNewDocument函數將調用虛函數DeleteContent函數;
6、爲view對象調用虛函數CView::OnInitialUpdate;
7、爲frame對象調用CFrameWnd::ActivateFrame以顯示the main frame window(有the menus,view window,control bars)。
 
The Document Class's OnNewDocument Function
構造函數所完成的工作越少越好,這樣構造函數出錯的機率就會越來越小。而CDocument::OnNewDocument 和 CView::OnInitialUpdate 是做初始化的好地方。在這裏你可以彈出一個MessageBox。如果出錯,OnNewDocument還可以返回FALSE。值得注意的是,OnNewDocument可以被調用很多次,所以有些指令需只執行一次的話,就需要做一個“first time” flag成員變量。
 
Connecting File Open to Your Serialization Code—The OnFileOpen Function
文件打開菜單映射到CWinApp::OnFileOpen函數,它將執行以下幾個步驟:
1、提示用戶選擇一個文件;
2、調用虛函數CDocument::OnOpenDocument,CDocument::OnOpenDocument打開文件,調用CDocument::DeleteContents,並且構造一個CArchive對象。隨後調用document的Serialize函數從archive中載入數據;
3、調用view的OnInitialUpdate函數。
 
Connecting File Save and File Save As to Your Serialization Code
文件保存和另存爲菜單映射到CDocument的OnFileSave函數,OnFileSave函數依次調用Serialize函數,它使用一個archive對象進行存儲。
 
The Document's "Dirty" Flag
CDocument有一個protected成員函數m_bModified。可以通過CDocument的函數SetModifiedFlag和IsModified訪問m_bModified。當新建一個document或者讀取完硬盤上的數據後,m_bModified被Application Framework設爲FALSE。當document的內容被改寫後要確保把m_bModified設爲TRUE。
 
小結:OnFileNewOnFileOpen都在Application類中,Application類裏面有DocumentTemplate,可以同時調動DocumentViewOnInitialUpdate)。

OnFileSaveOnFileSaveAs都在Document類中,它只需做Serialization,不牽扯View的操作,故不需要把它們放在Application類中。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章