Programming Microsoft Visual C++
You've seen many SDI applications that have one document class and one view class. We'll stick to a single view class in this chapter, but we'll explore the interrelationships among the application object, the main frame window, the document, the view, the document template object, and the associated string and menu resources.
The Windows Application Object
For each of your applications, AppWizard has been quietly generating a class derived from CWinApp. It has also been generating a statement such as this:
CMyApp theApp;
What you're seeing here is the mechanism that starts an MFC application. The class CMyApp is derived from the class CWinApp, and theApp is a globally declared instance of the class. This global object is called the Windows application object.
Here's a summary of the startup steps in a Microsoft Windows MFC library application:
- Windows loads your program into memory.
- The global object theApp is constructed. (All globally declared objects are constructed immediately when the program is loaded.)
- Windows calls the global function WinMain, which is part of the MFC library. (WinMain is equivalent to the non-Windows main functioneach is a main program entry point.)
- WinMain searches for the one and only instance of a class derived from CWinApp.
- WinMain calls the InitInstance member function for theApp, which is overridden in your derived application class.
- Your overridden InitInstance function starts the process of loading a document and displaying the main frame and view windows.
- WinMain calls the Run member function for theApp, which starts the processes of dispatching window messages and command messages.
You can override another important CWinApp member function. The ExitInstance function is called when the application terminates, after all its windows are closed.
Windows allows multiple instances of programs to run. The InitInstance function is called each time a program instance starts up. In Win32, each instance runs as an independent process. It's only incidental that the same code is mapped to the virtual memory address space of each process. If you want to locate other running instances of your program, you must either call the Win32 FindWindow function or set up a shared data section or memory-mapped file for communication.
The Document Template Class
If you look at the InitInstance function that AppWizard generates for your derived application class, you'll see that the following statements are featured:
CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CStudentDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CStudentView)); AddDocTemplate(pDocTemplate);
Unless you start doing fancy things with splitter windows and multiple views, this is the only time you'll actually see a document template object. In this case, it's an object of class CSingleDocTemplate, which is derived from CDocTemplate. The CSingleDocTemplate class applies only to SDI applications because SDI applications are limited to one document object. AddDocTemplate is a member function of class CWinApp.
The AddDocTemplate call, together with the document template constructor call, establishes the relationships among classesthe application class, the document class, the view window class, and the main frame window class. The application object exists, of course, before template construction, but the document, view, and frame objects are not constructed at this time. The application framework later dynamically constructs these objects when they are needed.
This dynamic construction is a sophisticated use of the C++ language. The DECLARE_DYNCREATE and IMPLEMENT_DYNCREATE macros in a class declaration and implementation enable the MFC library to construct objects of the specified class dynamically. If this dynamic construction capability weren't present, more relationships among your application's classes would have to be hard-coded. Your derived application class, for example, would need code for constructing document, view, and frame objects of your specific derived classes. This would compromise the object-oriented nature of your program.
With the template system, all that's required in your application class is use of the RUNTIME_CLASS macro. Notice that the target class's declaration must be included for this macro to work.
Figure 17-2 illustrates the relationships among the various classes, and Figure 17-3 illustrates the object relationships. An SDI application can have only one template (and associated class groups), and when the SDI program is running, there can be only one document object and only one main frame window object.
Figure 17-2. Class relationships.
Figure 17-3. Object relationships.
The MFC library dynamic construction capability was designed before the runtime type identification (RTTI) feature was added to the C++ language. The original MFC implementation goes beyond RTTI, and the MFC library continues to use it for dynamic object construction. See Appendix B for a description of MFC library dynamic construction.
The Document Template Resource
The first AddDocTemplate parameter is IDR_MAINFRAME, the identifier for a string table resource. Here is the corresponding string that AppWizard generates for EX17A in the application's RC file:
IDR_MAINFRAME "ex17a\n" // application window caption "\n" // root for default document name // ("Untitled" used if none provided) "Ex17a\n" // document type name "Ex17a Files (*.17a)\n" // document type description and filter ".17a\n" // extension for documents of this type "Ex17a.Document\n" // Registry file type ID "Ex17a Document" // Registry file type description
The resource compiler won't accept the string concatenations as shown above. If you examine the ex17a.rc file, you'll see the substrings combined in one long string.
IDR_MAINFRAME specifies one string that is separated into substrings by newline characters (\n). The substrings show up in various places when the application executes. The string 17A is the default document file extension specified to AppWizard.
The IDR_MAINFRAME ID, in addition to specifying the application's strings, identifies the application's icon, toolbar resources, and menu. AppWizard generates these resources, and you can maintain them with the resource editors.
So now you've seen how the AddDocTemplate call ties all the application elements together. Be aware, though, that no windows have been created yet and therefore nothing appears on the screen.
Multiple Views of an SDI Document
Providing multiple views of an SDI document is a little more complicated. You could provide a menu item that allows the user to choose a view, or you could allow multiple views in a splitter window. Chapter 20 shows you how to implement both techniques.
Creating an Empty DocumentThe CWinApp::OnFileNew Function
After your application class's InitInstance function calls the AddDocTemplate member function, it calls OnFileNew (indirectly through CWinApp::ProcessShellCommand), another important CWinApp member function. OnFileNew sorts through the web of interconnected class names and does the following:
- Constructs the document object but does not attempt to read data from disk.
- Constructs the main frame object (of class CMainFrame); also creates the main frame window but does not show it. The main frame window includes the IDR_MAINFRAME menu, the toolbar, and the status bar.
- Constructs the view object; also creates the view window but doesn't show it.
- Establishes connections among the document, main frame, and view objects. Do not confuse these object connections with the class connections established by the call to AddDocTemplate.
- Calls the virtual CDocument::OnNewDocument member function for the document object, which calls the virtual DeleteContents function.
- Calls the virtual CView::OnInitialUpdate member function for the view object.
- Calls the virtual CFrameWnd::ActivateFrame for the frame object to show the main frame window together with the menus, view window, and control bars.
Some of the functions listed above are not called directly by OnFileNew but are called indirectly through the application framework.
In an SDI application, the document, main frame, and view objects are created only once, and they last for the life of the program. The CWinApp::OnFileNew function is called by InitInstance. It's also called in response to the user choosing the File New menu item. In this case, OnFileNew must behave a little differently. It can't construct the document, frame, and view objects because they're already constructed. Instead, it reuses the existing document object and performs steps 5, 6, and 7 above. Notice that OnFileNew always calls DeleteContents (indirectly) to empty the document.
The Document Class's OnNewDocument Function
You've seen the view class OnInitialUpdate member function and the document class OnNewDocument member function in Chapter 16. If an SDI application didn't reuse the same document object, you wouldn't need OnNewDocument because you could perform all document initialization in your document class constructor. Now you must override OnNewDocument to initialize your document object each time the user chooses File New or File Open. AppWizard helps you by providing a skeleton function in the derived document class it generates.
It's a good idea to minimize the work you do in constructor functions. The fewer things you do, the less chance there is for the constructor to failand constructor failures are messy. Functions such as CDocument::OnNewDocument and CView::OnInitialUpdate are excellent places to do initial housekeeping. If anything fails at creation time, you can pop up a message box, and in the case of OnNewDocument, you can return FALSE. Be advised that both functions can be called more than once for the same object. If you need certain instructions executed only once, declare a "first time" flag data member and then test/set it appropriately.
Connecting File Open to Your Serialization CodeThe OnFileOpen Function
When AppWizard generates an application, it maps the File Open menu item to the CWinApp::OnFileOpen member function. When called, this function invokes a sequence of functions to accomplish these steps:
- Prompts the user to select a file.
- Calls the virtual function CDocument::OnOpenDocument for the already existing document object. This function opens the file, calls CDocument::DeleteContents, and constructs a CArchive object set for loading. It then calls the document's Serialize function, which loads data from the archive.
- Calls the view's OnInitialUpdate function.
The Most Recently Used (MRU) file list is a handy alternative to the File Open menu item. The application framework tracks the four most recently used files and displays their names on the File menu. These filenames are stored in the Windows Registry between program executions.
You can change the number of recent files tracked by supplying a parameter to the LoadStdProfileSetting function in the application class InitInstance function.
The Document Class's DeleteContents Function
When you load an existing SDI document object from a disk file, you must somehow erase the existing contents of the document object. The best way to do this is to override the CDocument::DeleteContents virtual function in your derived document class. The overridden function, as you've seen in Chapter 16 , does whatever is necessary to clean up your document class's data members. In response to both the File New and File Open menu items, the CDocument functions OnNewDocument and OnOpenDocument both call the DeleteContents function, which means DeleteContents is called immediately after the document object is first constructed. It's called again when you close a document.
If you want your document classes to work in SDI applications, plan on emptying the document's contents in the DeleteContents member function rather than in the destructor. Use the destructor only to clean up items that last for the life of the object.
Connecting File Save and File Save As to Your Serialization Code
When AppWizard generates an application, it maps the File Save menu item to the OnFileSave member function of the CDocument class. OnFileSave calls the CDocument function OnSaveDocument, which in turn calls your document's Serialize function with an archive object set for storing. The File Save As menu item is handled in a similar manner: it is mapped to the CDocument function OnFileSaveAs, which calls OnSaveDocument. Here the application framework does all the file management necessary to save a document on disk.
Yes, it is true that the File New and File Open menu options are mapped to application class member functions, but File Save and File Save As are mapped to document class member functions. File New is mapped to OnFileNew. The SDI version of InitInstance also calls OnFileNew (indirectly). No document object exists when the application framework calls InitInstance, so OnFileNew can't possibly be a member function of CDocument. When a document is saved, however, a document object certainly exists.
The Document's "Dirty" Flag
Many document-oriented applications for Windows track the user's modifications of a document. If the user tries to close a document or exit the program, a message box asks whether the user wants to save the document. The MFC application framework directly supports this behavior with the CDocument data member m_bModified. This Boolean variable is TRUE if the document has been modified (has become "dirty"); otherwise, it is FALSE.
The protected m_bModified flag is accessed through the CDocument member functions SetModifiedFlag and IsModified. The framework sets the document object's flag to FALSE when the document is created or read from disk and when it is saved on disk. You, the programmer, must use the SetModifiedFlag function to set the flag to TRUE when the document data changes. The virtual function CDocument::SaveModified, which the framework calls when the user closes the document, displays a message box if the m_bModified flag is set to TRUE. You can override this function if you need to do something else.
In the EX17A example, you'll see how a one-line update command UI function can use IsModified to control the state of the disk button and the corresponding menu item. When the user modifies the file, the disk button is enabled; when the user saves the file, the button changes to gray.
In one respect, MFC SDI applications behave a little differently from other Windows SDI applications such as Notepad. Here's a typical sequence of events:
- The user creates a document and saves it on disk under the name (for example) test.dat.
- The user modifies the document.
- The user chooses File Open and then specifies test.dat.
When the user chooses File Open, Notepad asks whether the user wants to save the changes made to the document (in Step 2 above). If the user answers no, the program rereads the document from disk. An MFC application, on the other hand, assumes that the changes are permanent and does not reread the file.