In-depth introduction to VC ++ (2)-the essence of MFC

Source: Internet
Author: User

I. Introduction

In the previous topic, a Windows application was completed manually. However, in actual development, most of us use existing class libraries to develop Windows applications. Microsoft Foundation Class (MFC) encapsulates Windows APIs into C ++ classes to simplify the development of programmers, programmers can effectively develop applications on the Windows platform. This topic will detail it.

2. Create an MFC program using the wizard

In addition to MFC, other open-source class libraries are provided to help effectively develop Windows applications. For example, QT is not developed by Microsoft. to better analyze MFC, next, let's use the MFC template and Wizard tool in Visual Studio to create an MFC-based single document (SDI) application.

Warning (suppress: 4985)

In the above Code, the _ tWinMain function is not the WinMain function I want. Is it wrong? For this question, the answer is no. We have not found an error. Here _ tWinMain is a macro definition. Press F12 to see that it represents WinMain. The macro definition source code is as follows (exists in the tchar. h header file ):

 _tmain      main _tWinMain   WinMain

In order to prove that the WinMain we found is the entry function we need to find, we can go to appmodul. in the cpp file, set a breakpoint in the _ tWinMain function and press F5 to run the SDIMFC program. We found that the SDIMFC program will stop at the breakpoint we just set, as shown in:

We have found the implementation of the WinMain function in MFC, but we have not figured out how the MFC program we created calls appmodul. in cpp, how does the _ tWinMain function relate the MFC class in the program to the WinMain function? Next let's take a look at the CSDIMFCApp class (as to why we think of this class, because it is suffixed with App, that is, the application, so we guess the program will first enter this class before entering the WinMain function ), double-click the class in the Class View and you will see the definition of the class in VS. You can see from the class definition that the CSDIMFCApp class inherits from the CWinAppEx class and the CWinAppEx class inherits from the CWinApp class, to prove that the CSDIMFCApp class code was executed before the WinMain function, we set a breakpoint for the constructor in the CSDIMFCApp class, and then press F5 to run the program, the program will first stop at the constructor of the CSDIMFCApp class, and then enter the _ tWinMain function (this breakpoint is the breakpoint we set earlier ). This raises another question: why does the program first call the CSDIMFCApp constructor? Since the constructor is called, it must define an object of this class. Then, we can find that in the CSDIMFCApp class, we define a global object theApp of the CSDIMFCApp type, which exists in SDIMFC. in the cpp file, the specific definition code is as follows:

CSDIMFCApp theApp; // 

Then we set a breakpoint at this global object, and then press F5 to debug and run the program. You will find that the program runs in the following sequence: theApp Global Object-> CSDIMFCApp Constructor (the constructor of its parent class will be called before calling the constructor of the derived class)-> _ tWinMain function. In the MFC program, theApp object uniquely identifies an application instance. Each MFC program has only one application object (theApp object ).

3.2 design and register window classes

Now we have found the WinMain function in MFC. Based on the content of the previous topic, next we will find the code for the window class and registration window class in the MFC application. In the previous topic, window classes and registration are defined in the WinMain function. Let's take a look at what the WinMain function in MFC has encapsulated for us, the WinMain function in MFC simply calls the AfxWinMain function. Let's take a look at the specific code of AfxWinMain:

       _In_ LPTSTR lpCmdLine,       ASSERT(hPrevInstance ==       nReturnCode = -     CWinThread* pThread =     CWinApp* pApp =            (!                     (pApp != NULL && !pApp->                     (!pThread->           (pThread->m_pMainWnd !=              TRACE(traceAppMsg, ,              pThread->m_pMainWnd->          nReturnCode = pThread->                      nReturnCode = pThread->              (AfxGetModuleThreadState()->m_nTempMapLock !=           TRACE(traceAppMsg, ,              AfxGetModuleThreadState()->       AfxUnlockTempMaps(-         }

The above code first calls the AfxGetThread function to obtain a pointer to the CWinThread type, and then calls the AfxGetApp function to obtain a pointer to the CWinApp type, then, call the AfxWinInit function to initialize AFX (the function prefixed with AFX is the Application Framework function, and the Application Framework). Then, the pApp calls the InitApplication function, this function mainly completes the internal management of MFC. The function is a virtual function, and the implementation in the CWinApp is (the function implementation code search can be viewed as described above ):

(CDocManager: pStaticDocManager! = (M_pDocManager === (m_pDocManager! =-> =View Code

Continue to call the InitInstance function of pThread. According to F12, this function is declared as a virtual function. According to the class polymorphism, The InitInstance function called in the AfxWinMain function is the InitInstance function of CSDIMFCApp, the code for defining this function is:

 /                       InitCtrls.dwSize =                InitCtrls.dwICC =     InitCommonControlsEx(&               (!                                                                    SetRegistryKey(_T(     LoadStdProfileSettings();               ttParams.m_bVislManagerTheme =     theApp.GetTooltipManager()->         RUNTIME_CLASS(CMFCToolTipCtrl), &               CSingleDocTemplate*     pDocTemplate =            RUNTIME_CLASS(CMainFrame),              (!                                      (!                    m_pMainWnd->     m_pMainWnd->                }

In the above Code, m_pMainWnd refers to the window created for us and is defined as a pointer to the CWnd type according to F12. The Cwnd class is a standard window class pre-defined by MFC, now we have found the window class in the MFC program. Next we will find how to register the window in the MFC. In the MFC, the registration of the window class is completed by the AfxEndDeferRegisterClass function, it is defined in Wincore. in the cpp file, the AfxEndDeferRegisterClass function uses the AfxRegisterClass function (this function is also defined in wincore. in the cpp file) to register the window class. Due to space issues, the definition source code of its function is not pasted here. You can view it on the local machine.

3.3 create dialog box

We have found the encapsulation of the MFC design window and registration. The next step is how to create a window in the MFC program. This function is completed by the CreateEx function of the CWnd class in the MFC, the function is declared in afxwin. the specific code in the H file is as follows:

 x,  y,  nWidth, = NULL);

The implementation code is in wincore. in the cpp file, the CMainFrame window is created in our program. The CMainFrame class inherits from CFrameWndEx, and the class inherits from CFrameWnd. the Create function of the CFrameWnd class calls the CreateEx function internally, the Create function of CFrameWnd is called by the LoadFrame function of the CFrameWnd class. The Create function declaration of the CFrameWnd class is located in the afxwin. h file, and its implementation code is located in the winfrm. cpp file. The implementation code is as follows:

RECT & ** = (lpszMenuName! = HINSTANCE hInst = (hMenu =: LoadMenu (hInst, lpszMenuName) =, = lpszWindowName ;(! -Rect. left, rect. bottom -->, (hMenu! =View Code3.4 display and update Windows

The content of the InitInstance function in CSDIMFCApp class contains the code for displaying and updating Windows. The specific code is as follows:

  m_pMainWnd->->UpdateWindow();
3.5 message loop

The Run function of the CWinThread class is used to complete the message loop task. This function is called in the AfxWinMain function and is defined in the thrdcore. cpp file. Its definition code is as follows:

* PState = BOOL bIdle = (bIdle &&! : PeekMessage (& (pState-> (! OnIdle (lelecount ++ = FALSE ;(! (IsIdleMessage (& (pState-> = (: PeekMessage (& (pState->View Code3.6 Window Process Functions

In the AfxEndDeferRegisterClass function, there is a line of such code (marked in red below ):

    AFX_MODULE_STATE* pModuleState =&= ~pModuleState-> (fToRegister == = &wndcls, , (WNDCLASS));       wndcls.hInstance == afxData.hcurArrow;
.....
}

However, in MFC, not all messages are delivered to the default Window Process DefWindowProc for processing, but a process called to process various messages is used, the message ing mechanism of MFC allows you to add a message processing function for a class through the Class Wizard. For specific operations, right-click a class in the Class View and select the Class Wizard, switch to the Message option card in the pop-up MFC wizard form to add a message processing function, which is in the CMainFrame execution Class Wizard:

This process is similar to adding an event processing function through a control event in WinForm in. NET. (Events in WinForm correspond to messages in MFC ).

So far, we have analyzed the running mechanism of the MFC program, and we can find that the process is consistent with the previous topic introduction, but we do not need to implement these processes in the MFC, these are all encapsulated by the MFC framework, which reduces the workload of developers and puts more time on the business logic of the Implementation Program. Let's take a look at the running process of the MFC program:

Iv. Document/View Structure

In addition to the main framework window, the MFC program we created has a class window corresponding to the CView class. The Framework Window is a parent window of the class window, shows the relationship between them. The main frame window is the part included in the entire application window, while the class window is just a blank area in the main frame window.

There is also a CSDIMFCDoc class in the MFC program we created earlier, which is derived from the CDocument class. The base class of the latter is c0000target, And the c0000target is derived from the CObject class, we can know that the CSDIMFCDoc class is not a window class, but actually a document class.MFC provides a Document/View structure (Document/View). Here the Document refers to the CDocument class, while the View refers to the CView class. When designing MFC, Microsoft should consider that the data itself should be separated from its display (this is reflected in many Microsoft technologies, such as Asp.net MVC ), therefore, the document and view structure are used to implement this idea. Data storage and loading are completed by the document class, and data display and modification are completed by the View class, thus separating data management and display methods..

V. Summary

At this point, the content of this topic is over. This topic mainly analyzes the running mechanism of the MFC framework, and finds that the MFC application follows the corresponding process of the Win32 SDK program, these include the design window class, registration window class, creation window, display and update window, message loop, and window processing process function, but these operations are encapsulated by MFC itself.

 

Related Article

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.