In-depth understanding of the text block/View Structure in MFC
Topic: in-depth understanding of the text block/View Structure in MFC
Content:
Visual c ++ 6.0 is favored by programmers for its powerful functions and friendly user interfaces. However, in the current Microsoft basic class library version 4.2, there are approximately 200 classes and thousands of functions. In addition, Microsoft has hidden some technical details, it makes it very difficult for people to study MFC in depth.
MFC Appwizard can generate three types of applications: Dialog Box-based applications, single-document applications (SDI) and Multi-document applications (MDI ). The structure of the first two is relatively simple. This article will not go into details. The author intends to analyze the process of some functions from the documentation/visual structure in MFC, and solve some common problems in the preparation of the MDI application.
(1) understand the document/View Structure
The MFC application model has undergone considerable development over the years. There is a period in which it is just a simple model that uses the application object and the main window object. In this model, the data of the application is kept in the framework window class as a member variable. In the customer area of the Framework Window, the data is submitted to the monitor. With mfc2. The advent of 0, a new way of application structure-the emergence of the MFC documentation/visual structure. In this structure, the heavy tasks of cframewnd are assigned to several different classes, realizing the separation of data storage and display. Generally, an application that uses a document/view structure should consist of at least the following objects:
. An application is a cwinapp derived object that acts as a container for all applications. The application assigns all subprograms to a message along the message ing Network.
. The Framework Window is a cfrmewnd derived object.
. A document is a cdocument derived object that stores application data and provides the information to the rest of the application.
. A window is a cview derived object. It is aligned with the user area of its parent frame window. Windows allows you to input applications and display associated document data.
Normally, application data is stored in the Framework Window of the simple model. In document/visual mode, the data is moved into an independent data object called document. Of course, documents are not necessarily text. Documents are abstract terms that can represent datasets used by applications. The user input processing and Graphic Output Functions shift from the frame window to the view. A separate window completely masks the customer area of the frame window, which means that even if the programmer draws the image directly to the customer area of the frame window, the view still masks the painting and no information appears on the screen. Therefore, the output must pass through the view. The Framework Window is just a view container.
The cdocument class supports document creation and archiving, and provides interfaces for applications to control their data. The MDI application can process multiple types of documents. Each type of documents has an associated document template object. Document objects reside behind the scenario and provide information displayed by view objects. The document must have at least one associated view. A view can only be associated with one document.
In document/view mode, object creation is managed by document templates, which are derived from cdoctemplate, and framework windows, documents, and views are created and maintained.
MFC calls the command processing program to respond to events that occur in the application. The priority of command sending is:
Activity view-> Framework Window-> document-> application-> default Window Process (defwindowsproc)
In short, in document/view mode, the document and view are separated, that is, the document is used to save data, and the document is used to display the data. Document templates maintain Kansai between them. This document/view structure is particularly useful when developing large software projects.
(2) understand the relationship between various types related to the document/view structure.
In document/view applications, cwinapp objects own and control document templates, which generate documents, framework windows, and windows. This relationship is shown in (1:
From the user's perspective, "View" is actually a common window. Like other Windows based on Widnows, people can change its size, move it, or close it at any time. From the programmer's point of view, it is actually an object of the class derived from the cview class in the MFC class library. Document objects are used to save data, whereas object objects are used to display data and allow editing of log data. SDI or MDI document classes are derived from the cdocument class. They can have one or more visual classes which are ultimately derived from the cview class. The object has only one associated document object. The cview: getdocument function contained in the object allows the application to obtain the associated document in the view. Accordingly, applications can access document-class membership functions and public data members. If the object receives a message, the user enters new data in the editing control. In this case, the object must be notified to update the internal data.
If the document data changes, all views must be notified so that they can update the displayed data accordingly. Cdocument: The updateallviews function can complete this function. When this function is called, The cview: onupdate function of the derived class is triggered. Generally, the onupdate function accesses the document, reads the document data, and updates the data members or controls to reflect the changes in the document. In addition, the onupdate function can be used to make some customer zones of the view ineffective, so as to trigger the cview: ondraw function, and redraw the window using the document data.
In an MDI application, you can process multiple document types, that is, multiple document templates. Each template can have multiple documents, and each document can be displayed in multiple views. For ease of management, the pointer list at the next level is often retained. (2) As shown in:
Explanation:
(1) Each application class (cwinapp derived class) retains and maintains a pointer list of all document templates. This is a linked list structure. The application dynamically allocates a cmultidoctemplate object for each document type to be supported,
Cmultidoctemplate (uint nidresource,
Cruntimeclass * pdocclass,
Cruntimeclass * pframeclass,
Cruntimeclass * pviewclass );
In the cwinapp: initinstance member function of the application class, each cmultidoctemplate object is passed to cwinapp: adddoctemplate. This function adds a document template to the list of available document templates for applications. Function prototype:
Void adddoctemplate (cdoctemplate * ptemplate );
The application can use cwinapp: getfirstdoctemplatepostion to obtain the location of the first document template registered by the application. Use this value to call the cwinapp: getnextdoctemplate function to obtain the pointer of the first cdoctemplate object. The original function is as follows:
Position getfirstdoctemplate () const;
Cdoctemplate * getnextdoctemplate (Position & Pos) const;
The second function returns the document template identified by the POS. Position is a value defined by MFC for iteration or object pointer retrieval. With these two functions, the application can traverse the entire document template list. If the retrieved document template is the last in the template list, the POs parameter is set to null.
(2) A document template can have multiple documents. Each document template retains and maintains a pointer list for all corresponding documents. The application can use the cdoctemplate: getfirstdocposition function to obtain the location of the first document in the document set related to the document template, and use the position value as the cdoctemplate :: getnextdoc parameters are used to repeatedly traverse the list of template-related documents. Function prototype:
Viaual position getfirstdocposition () const = 0;
Visual cdocument * getnextdoc (Position & rpos) const = 0;
If the list is empty, rpos is set to null.
(3) In this document, you can call cdocument: getdoctemplate to obtain a pointer to this document template. The original function is as follows:
Cdoctemplate * getdoctemplate () const;
If the document does not belong to document template management, the return value is null.
(4) A document can have multiple views. Each document retains and maintains a list of all associated views. Cdocument: addview connects a view to a document, adds the view to the list of associated documents, and points the document pointer to the document. When a file/New, file/open, Windows/new, or window/split command connects a newly created object to the document, MFC automatically calls this function, the framework associates the document with the view through the document/view structure. Of course, programmers can also call this function according to their own needs.
Virtual position getfirstviewposition () const;
Virtual cviw * getnextview (Position & rposition) cosnt;
The application can call cdocument: getfirstviewposition to return the location of the first view in the list of views associated with the call document, and call cdocument: getnextview to return the view at the specified position, set the value of rpositon to the position value of the next view in the list. If the result is regarded as the last view in the list, the rposition is set to null.
When a new view is added or deleted in the document, MFC calls the onchangeviewlist function. If the deleted view is the last view of the document, delete the document.
(5) One view can only have one document. In the view, call cview: getdocument to obtain a pointer to the view document. The original function is as follows:
Cdocument * getdocument () const;
If this view is not in the same phase as any document, null is returned.
(6) The MDI Framework Window can call cframewnd: getactivedocument to obtain the cdocument pointer connected to the current active video. The original function is as follows:
Virtual cdocument * getactivedocument ();
(7) Call cframewnd: getactiveview to obtain the pointer to the activity view connected to the cframewnd Framework Window. if the pointer is called by the cmdiframewnd Framework Window, null is returned. In the MDI frame window, you can call mdigetactive to locate the active MDI child window, and then locate the activity view of the Child Window. The original function is as follows:
Virtual cdocument * getactivedocument ();
(8) The MDI frame window calls cframewnd: getactiveframe to obtain a pointer to the Child Window of the Multi-document window that directs to the MDI frame window.
(9) cmdichildwnd calls getmdiframe to obtain the MDI frame window (cmdiframewnd ).
(10) cwinapp calls afxgetmainwnd to get a pointer to the main activity window of the application.
The following code uses the access relationship between cdoctemplate, cdocument, and cview to traverse the entire document template, document, and view.
Cmyapp * pmyapp = (cmyapp *) afxgetapp ();
Position P = pmyapp-> getfirstdoctemplateposition ();
While (P! = NULL ){
Cdoctemplate * pdoctemplate = pmyapp-> getnextdoctemplate (P );
Position p1 = pdoctemplate-> getfirstdocposition ();
While (P1! = NULL ){
Cdocument * pdocument = pdoctemplate-> getnextdoc (P1 );
Position P2 = pdocument-> getfirstviewposition ();
While (P2! = NULL ){
Cview * pview = pdocument-> getnextview (P2 );
}
}
}
(Figure 4) traverse the entire document template, document, and view
Programmers can call afxgetapp () anywhere in an application to obtain the object pointer of the application. As this article focuses on the relationship between documents and views, the relationships between framework Windows cannot be fully listed, so you can check the relevant documents.
(3) understand the procedures of cwinapp: onfilenew, cwinapp: onfileopen and window/New.
(1) A simple process of the cwinapp: onfilenew and cwinapp: onfileopen functions.
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
In the cwinapp: onfile/new or cwinapp: onfileopen function, the core operation is the cdoctemplate: OpenDocument function. Its function prototype is:
Virtual cdocument * cdoctemplate: opendocumentfile (lpctstr lpszpathname, bool bmakevisible = true) = 0;
Figure (4) process of the function after the star number is marked. The following is a brief introduction:
(1) The cdoctemplate: createnewdocument function creates a new document. Its type is related to the document template, and the cdoctemplate: adddocument function is used to add it to the document pointer list of the document template. At this time, the constructor of the document class is executed, and the program can initialize the document here.
(2) function cdoctemplate: createnewframe calls the constructor of the MDI subwindow class (cmdichildwnd) to generate an MDI subwindow object. Call javasichildwnd: precreatewindow. Then, a ccreatecontext object is generated. (ccreatecontext is a structure used by the MFC framework. It associates the components that constitute the document with the visual component. I will introduce it in detail later .) And pass the object value to the cmdichildwnd: oncreateclient function. MFC calls this function to create one or more cview objects with the information provided by the ccreatecontext object. In this case, the number of constructor IDs for each view is called in sequence.
(3) then, determine whether the lpszpathname is null. There are two scenarios:
(A) if it is null, it indicates that you want to create a new document: Call the setdefatitle title function to load the default title of the document and display it in the document title bar; then run cdocument: onnewdocument. This function calls deletecontents to ensure that the document is empty and then the new document is cleaned. This function can be reloaded.
(B) Otherwise, it indicates to open an existing document: Call cdocument: onopendocument to open the specified file; execute deletecontext to ensure that the document is empty; call cobject :: serialize reads the content of the file. (Programmers can read files here. Of course, you can also read files in cdocument: onopendocument ). Set the document to clean. Finally, call cdoctemplate: setpathname and add the file name to the latest file list.
(4) Call the cdoctemplate: initialupdateframe function, so that each of the frames in the window receives the oninitialupdate call. The main view of the frame window (sub-window ID equals afx_idw_pane_first) is activated. The programmer can initialize the object.
(2) program flow of the window/new command
When a subwindow exists in the main frame window, select the window/new command to generate the image of the subwindow of the activity. They have the same document template and the same document. The process is as follows:
The process of executing window/New is similar to that of file/New. The difference is that file/new needs to create a new document, while window/New is to obtain the existing document of the MDI subwindow. Therefore, the previous view and the generated view after new are the view of this document, and the content of this document is displayed. When the cdocument: updateallviews function is called, all the onupdate functions of them (depending on) will be activated. In this case, there will be more than one view in the view pointer list of this document (the specific number depends on the number of window/new executions ). You can use the code in (Figure 3) to track program results.
(4) discussion of several situations
As mentioned above, I have analyzed the relationship between documents and views in MFC. below, I will discuss the relationship based on the actual situation:
(1) how to select a document template and view and document as required.
In a common MDI application, there is only one document template. A programmer can open only one type of document. Therefore, programmers only need to call file/new or file/open to create or open a file. The relationship between documents, views, and framework windows is controlled by the Document Template behind the scenes, you do not need to operate the document template. However, if an application needs to process multiple types of documents and the type of documents to be opened must be manually controlled by the programmer, the programmer must program the document template.
For example, the author needs to process Avi and BMP file types. Avi and BMP data are stored in different formats and cannot be described in the same data structure. Therefore, it is inappropriate to store all their data into a document. At the same time, Because Avi is an image sequence and BMP is only an image, their display must be different, that is, their door views are different. Based on this, I decided to create two sets of document templates, two sets of framework windows, two sets of documents and two sets of views for storing and displaying Avi and BMP data respectively. The program can process Avi and BMP respectively based on the selected file name. The procedure is as follows:
(Step 1) Add a document template member variable to the derived class of the application class (cwinapp) to perform operations on the document template.
Class c3dlcsapp: Public cwinapp
{... ...
Public:
Cmultidoctemplate * m_pavidoctemplate;
Cmultidoctemplate * m_pbmpdoctemplate;
}
(Step 2) Add a menu response in the main framework:
Void cmainframe: onfileopen (){
Cfiledialog my (true );
If (My. domodal () = idok ){
Cstring filename = My. getpathname ();
Cstring fileext = My. getfileext ();
If (fileext = "Avi") | (fileext = "Avi ")){
Cmyapp * pmyapp = (cmyapp *) afxgetapp ();
Cmultidoctemplate * pavidoctemplate = pmyapp-> m_pavidoctemplate;
Pavidoctemplate-> opendocumentfile (filename );
}
Else if (fileext = "BMP") | (fileext = "BMP ")){
Cmyapp * p3dlcsapp = (cmyapp *) afxgetapp ();
Cmultidoctemplate * pdatdoctemplate = pmyapp-> m_pbmpdoctemplate;
Pdatdoctemplate-> opendocumentfile (filename );
}
Else {
Afxmessagebox ("yor select a file not supported! ");
Return;
}
}
}
The pen uses the suffix of the file name entered by the user as the branch condition. If the file is an AVI file, the document template about the AVI file is obtained first, and then the cdoctemplate: openupdateframe (lpszfilename) is called) function to open this document. As analyzed above, this function will generate new documents, new frameworks, create views in javasichildwnd: oncreateclient, and finally send initialization messages to all the views in the framework, display it on the screen. If it is a BMP file, the operation is similar.
Of course, programmers can also perform this operation anywhere in the program: Get the Application Object Pointer through the global function afxgetapp, and get the corresponding document template pointer.
Because the Application Generated by Appwizard calls cwinapp: onfilenew by default, a new blank window is displayed on the main framework when the program starts execution. To remove this empty window, you only need to reload the cwinapp: onfilenew function and do not require any code.
(2) splitting window and document/View Structure
A document can have multiple views, and a split window is a method to express multiple views. The split window is represented by the csplitterwnd class. For the window, the csplitterwnd object is a real window, which occupies the client region of the Framework Window completely, the window port occupies the window area of the split window. The split window does not participate in the Command transfer mechanism. The window in the window is logically connected to its frame window.
Split windows can be divided into dynamic and static. The former is relatively simple. This article only discusses the latter. To create a split window, follow these steps:
(Step 1) Declare the member variables in the Framework Window to operate the split window.
Class cmyframe: Public policichildwnd
{... ...
Csplitterwnd m_splitter;
Csplitterwnd m_splitter2;
}
(Step 2) Reload the cmdichildwnd: oncreateclient function to create a split window.
Bool cmyframe: oncreateclient (lpcreatestruct lpcs, ccreatecontext * pcontext)
{
Bool BTN = m_splitter.createstatic (this, 1, 2 );
BTN | = m_splitter.createview (100,100, runtime_class (cavidispview), csize (), pcontext );
M_splitter2.createstatic (& m_splitter,
2, 1,
Ws_child | ws_visible | ws_border,
M_splitter.idfromrowcol (0, 1 ));
BTN | = m_splitter2.createview (0, 0, runtime_class (cbmpview ),
Csize (100,100), pcontext );
BTN | = m_splitter2.createview (1, 0, runtime_class (caviview ),
Csize (100,100), pcontext );
Return BTN;
// Return response ichildwnd: oncreateclient (lpcs, pcontext );
}
The original form of the cframewnd: oncreateclient function is:
Virtual bool oncreateclient (lpcreatestruct lpcs, ccreatecontext * pcontext );
The saved javasichildwnd: oncreateclient function calls the cframewnd: createview function to create a view based on the information provided by the pcontext parameter. You can reload this function, load the value passed in the ccreatecontext object, or change the creation method controlled in the main customer area of the Framework Window. In the preceding procedure, the author creates three split windows. For example, if you open a document named "A. Avi", the document will have three views and a Framework Window. If the window/new operation is performed, there is a document, 6 views, and 2 framework windows. If this document calls the cdocument: updateallviews function, all the cview: onupdate functions of the six views will be stimulated.
(3) about ccreatecontext.
Ccreatecontext is a structure used by the MFC framework. It associates components that constitute documents/views. This structure includes the pointer to the document, Framework Window, view, and document template. It also contains a pointer to cruntimeclass to specify the type of the created view. Its data members are as follows:
M_pnewviewclass: pointer to the cruntimeclass of the created context.
M_pcurrentdoc: pointer to the document object, which is associated with the new view.
M_pnewdoctemplate: pointer to the document template associated with the creation of the Framework Window.
M_plastview: point to an existing view, which is the new view model.
M_pcurrentframe: points to an existing frame window, which is the model of the newly generated frame window.
Programmers can create more flexible views by changing the value of the ccreatecontext object. Due to the complexity of the process, I will not introduce it again. Readers can refer to the relevant VISUAL C ++ help documentation.
(5) Concluding remarks
The document/View Structure of Visual C ++ 6.0 represents a new programming method. Its core is the separation of documents and views, that is, the separation of data storage and display (operation. In the MFC class library, the relationships between objects are complex. However, once you have a deep understanding of them, you will find that they are interrelated and accessible to each other. If you want to design a flexible and robust application, you must have an in-depth understanding of MFC. Tracking the original code is a good method. The relationship between documents and views is indeed very complex. If you can know where each function is called and what operations are performed, you will be able to write beautiful applications.