First look at MFC (MFC operating mechanism, which is explained by Sun Xin C ++ in the third lecture)

Source: Internet
Author: User

With a certain degree of Windows 32 programming knowledge, you can learn MFC.

Before learning MFC, you must understand what is the message loop in windows32 programming. MFC is actually an encapsulation of Windows API functions.

 

In Windows programming, creating a window involves the following four processes (if you do not understand it, please refer to the blog for a glimpse at Win32)

1. Design a window class; 2. register the window class; 3. Create a window; 4. Display and update Windows.   Similarly, the same is true in MFC. It's just encapsulation. Many people think that MFC is hard to learn. Why can't they write their own programs while reading books? Because there is no mechanism to understand the principles of MFC. There are many books related to VC ++ on the market, but there are few books that give a thorough understanding of the principles of MFC. Similarly, winmain is also an entry function. For details about the specific process, see the third lecture of Sun Xin video 20.  One of the questions that sun Xin raised was: Defines a subclass object in a global variable...
# Include <iostream> # include <string> using namespace STD; class person {public: person * P; person () {P = this; // save this pointer} virtual void say () {cout <"Person's say ()" <Endl ;}}; class student: public person {public: student () {} void say () {cout <"Student's say ()" <Endl ;}}; student s; int main () {S. p-> say (); // return 0 is called here ;}
  Do not do anything. Use the Wizard to generate an MFC window. The following is the structure diagram, which has five classes. Yes. C at the beginning indicates class, C + project name + (app, Doc, view ...)

Cmainframe indicates a window (main form, including the title bar, menu ...), xxapp indicates the application, xxdoc indicates the document class (loading data to separate data storage and operations), and xxview also indicates a window (equivalent to the windows customer zone)

 

Let's take a look at the main inheritance relationships of classes in MFC:

Because the inheritance tree is too large, only the inheritance relationships of cwnd are listed here.

 

 

In the API, createmediawex and createwindow are almost the same, and ex indicates expansion. An additional parameter is provided.

The following uses API to simulate cwnd

Just Simulation

// The following is an encapsulation API function class cwnd {public: bool createex (DWORD dwexstyle, // extended window stylelpctstr lpclassname, // registered class namelpctstr lpwindowname, // window namedword dwstyle, // window styleint X, // horizontal position of your Wint y, // vertical position of your Wint nwidth, // window widthint nheight, // window heighthwnd hwndparent, // handle to parent or owner when whmenu hmenu, // men U handle or child identifierhinstance hinstance, // handle to application instancelpvoid lpparam // window-creation data); bool showwindow (INT ncmdshow); bool updatewindow (); public: hwnd m_hwnd;}; bool cwnd: createex (DWORD dwexstyle, // extended window style maid, // registered class name maid lpwindowname, // window name DWORD dwstyle, // window style int X, // horizontal position Of Window int y, // vertical position of window int nwidth, // window width int nheight, // window height hwnd hwndparent, // handle to parent or owner window hmenu, // menu handle or child identifier hinstance, // handle to application instance lpvoid lpparam // window-creation data); {m_hwnd =: createmediawex (dwexstyle, lclassname, lpwindowname, dwstyle, X, Y, nwidth, nheight, hwndparent, h Menu, hinstance, lparam); If (m_hwnd! = NULL) return true; elsereturn false;} bool cwnd: showwindow (INT ncmdshow) {return: showwindow (m_hwnd, ncmdshow); // calls the SDK global function, add: indicates global} bool cwnd: updatewindow () {return: updatewindow (m_hwnd);} int winapi winmain (hinstance, // handle to current instance hinstance hprevinstance, // handle to previous instance lpstr lpcmdline, // command line int ncmdshow // show state) {wndclass; wndclass. cbclsextra = 0; wndclass. cbwndextra = 0; wndclass. hbrbackground = (hbrush) getstockobject (white_brush); wndclass. hcursor = loadcursor (null, idc_arrow); wndclass. hicon = loadicon (null, idi_error); wndclass. hinstance = hinstance ;... cwnd; cwnd. createex (dwexstyle ,...,...); cwnd. showwindow (ncmdshow); cwnd. updatewindow (); While (getmessage (& MSG, null, 0, 0) {translatemessage (& MSG); dispatchmessage (& MSG );}...}

 

The following is a major play (reference of a senior friend, too detailed)

Key points: MFC Operating Mechanism
  
Tip: If you don't want to understand the internal running process, you can skip this chapter. You can refer to the interface design below and then look back at this chapter, which may be more profound.
The focus of this and last course is the creation process of the window class of MFC. It should be explained repeatedly: The program of MFC and the program of C language. From the principle of execution, is completely consistent.
By grasping this point, it is easier to understand the running mechanism of the MFC program.
The main function in C is equivalent to the winmain function in MFC.
If you are interested, you can use the breakpoint settings of VC to track the functions described below to understand the execution sequence.
  
1. C language execution steps
In C, the steps are as follows:
1. Global variable Memory Allocation
2. Enter the main function.
  
Ii. MFC program running steps (mainly initialization)
  
Open an MFC Appwizard (exe) project and track its execution steps. The following sequence is displayed:
1) global variable definition in cxxapp
Cxxapp theapp;
2) Call the cxxapp Constructor
Cxxapp: cxxapp (){}
3) enter the winmain function (_ twinmain is a macro and its value is winmain)
_ Twinmain (){}
  
4) Complete initialization: including window class registration, window generation, display, and update
Pthread-> initinstance ()
  
For the MFC program, mainframe, view, toolbar, controlbar, etc. are all windows, so the following window registration and creation, display, and so on need to be called multiple times, each corresponding to a window
  
(1) Registration window class
  
Afxenddeferregisterclass
  
(2) create a window
  
Cmainframe: precreatewindow () // It is an opportunity for us to modify window attributes.
  
Cframewnd: Create ()
  
(3) message loop
  
Pumpmessage ()
  
Supplement 1:
  
In MFC, more steps are required to define global variables because (window) class definition is involved.
  
If global variables involve class definitions (similar to Type Definitions in C), follow these steps (taking the window class of MFC as an example)
  
1) Design a window class
  
2) Registration window class
  
3) create a window
  
4) display and update window
  
5) message loop
  
  
  
Supplement 2: other notes
  
1. Each MFC program has only one class (Application class) derived from the winapp class, and only one instance from the application class, indicating the application itself. In a Win32 program, the application is represented by the winmain entry function (represented by an example number of an application ). In an MFC-based application, an application object is generated to uniquely represent an application.
  
2. The _ twinmain function calls the afxwinmain () function to complete its functions. (Afx * prefix indicates that this is an application framework function and a global function. The application framework is a framework model that aids in generating applications and organically integrates some classes, we can design our own applications based on these class functions ).
  
3. Design window class: In MFC, we have designed several default window classes. Based on the selection of different applications, we call the afxenddeferregisterclass () function to register the selected window class.
  
4. precreatewindow () is a virtual function. If a subclass exists, it calls the subclass.
  
5. The create‑wex () function parameters are exactly the same as those of the createstruct struct. the correspondence between the create‑wex () function and the createstruct struct parameters enables us to use the precreatewindow (CS) function before creating a window) modify the CS struct to modify the appearance of the window.
  
6. Pay attention to the two functions.
  
: The translatemessage (& m_msgcur) function converts messages (such as keyboard messages ).
  
: The dispatchmessage (& m_msgcur) function distributes messages to the callback function in the window for processing (in fact, the dispatched messages are mapped to messages and processed by the message response function .)
  
7. The View window is considered as a subwindow of the cmainfram class window. The document class is a document class. The DOC-VIEW structure separates the data itself from its display.
  
The document class is used for data storage and loading. The View class is used for data display and modification.
  
8. The cteapp: initinstance () function organizes the document class, View class, and framework class together through the document template. The statement is as follows:
  
Csingledoctemplate * pdoctemplate;
Pdoctemplate = new csingledoctemplate (
Idr_mainframe,
Runtime_class (ctedoc ),
Runtime_class (cmainframe), // main SDI frame window
Runtime_class (cteview ));
Adddoctemplate (pdoctemplate); // Add to template
  
Supplement 3: The Source File Location of the MFC function is involved in this lesson.
  
Root directory
  
Find the location where you install MFC under vc98, for example, D: \ Program Files \ Microsoft Visual Studio \ vc98 \ MFC on my computer. The following provides the relative path.
  
  
  
Cwinapp constructor: MFC => src => appcore. cpp
Afxwinmain: MFC => src => winmain. cpp
Afxenddeferregisterclass: MFC => src => appcore. cpp
Cframewnd: precreatewindow () function file: MFC => src => winfrm. cpp
Cframewnd: Create () function path: MFC => src => winfrm. cpp
Cwnd: createex () function path: MFC => src => wincore. cpp
Cwinthread: Run () method path: MFC => src => thrdcore. cpp

Create button

1. Create in cmainframe

Double-click cmainframe to add a data member, cbutton m_btn

Add the following code in the oncreate method:

m_btn.Create(TEXT("first Button"),BS_PUSHBUTTON|WS_CHILD,CRect(0,0,100,100),this,123);m_btn.ShowWindow(SW_NORMAL);

 

2. Create in cxxview

Double-click cxxview to add a data member, cbutton m_btn

Right-click cxxview and add windows message handler to add wm_create message processing, and then generate the oncreate function.

Add the following code to the oncreate function:

m_btn.Create(TEXT("Button2"),BS_PUSHBUTTON|WS_CHILD|WS_VISIBLE,CRect(0,0,100,100),this,123);

The effects of the two codes are equivalent:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.