Getting Started with the MFC application framework

Source: Internet
Author: User

1 MFC overview

As implies, the MFC application framework is based on the framework of MFC, the application framework of this program is built in the program structure of the organization is completely different from the previous Win32 SDK programming method. Since its inception in the early 1990s, MFC has been trying to encapsulate Windows API functions into each logical class in a class library. This encapsulation of MFC does not simply group and package API functions, but rather attempts to implement all of the system policies through classes. With the addition of more and more system functions, the scale of MFC is expanding, now includes more than 200 classes, covering the general Windows class, document/Video framework, OLE, database, Internet, and distributed functionality, and other aspects of the basic content. Such a solid program development Foundation undoubtedly greatly facilitates the development of Windows programs for programmers.

MFC offers quite a number of different functional classes to suit the widest possible needs. The vast majority of MFC classes are derived directly or indirectly from the CObject class, and the CObject class provides three important feature support for its derived classes: persistence (serialization) support, Runtime (Run-time) class information Support and diagnostics (Diagnostic) debugging support, and so on. Where persistence is the process of outputting or entering persistent data from a class object into an external storage medium, such as a disk file, in a stream, run-time class information (Run-time class information, RTCI) You can retrieve the class name of an object and some other information about the object at run time. RTCI is also another important tool in C + +, except for the runtime type information (Run-time type Information,rtti) mechanism, and diagnostic and debugging support as part of the CObject class, You can perform a validation check when implementing CObject derived classes and output state information to the Debug window.

Not all functions provided by MFC are class member functions, and MFC also provides a series of global functions prefixed with AFX. Class member functions can only be used in the context of the class object to which they belong, but these AFX functions are available directly at any time, anywhere. The following table lists several of the more important AFX functions:

Name of function Function description
Afxabout Terminates an application unconditionally, usually in the event of an error that cannot be answered
AfxBeginThread Create a new thread and start executing
AfxEndThread Terminates the currently executing thread
AfxMessageBox Display a Windows message window
AfxGetApp Returns a pointer to an Application object
AfxGetAppName Return application Name
AfxGetMainWnd Returns a pointer to the main application window
AfxGetInstanceHandle Returns a handle that identifies the current application instance
AfxRegisterWndClass Registering a user-defined window class for an MFC application

2 MFC encapsulation of API functions

If the reader has had the SDK development experience, will certainly have the cumbersome programming way and a lot of Win32 API function calls deep feeling. The API functions of all the different functions are put together in the form of global functions, because the number of API functions is relatively large, so whether it is learning or use is a certain difficulty. In contrast, MFC class libraries built on API functions can greatly simplify programming by encapsulating the classification of related API functions, and Windows applications written with MFC classes need only a small amount of work to accomplish the same task.

Many API functions are encapsulated by MFC into more than 200 classes based on their functionality, which basically covers the most likely functionality for Windows programming. Since the encapsulated MFC class too many, here can not be described here, the following is the more important CObject class and CWnd as an example of the API functions of the package to do a brief introduction.

The CObject class is one of the most important and basic classes in MFC, which does not support multiple inheritance, and the derived class can have only one CObject base class. The CObject class is at the top of the class hierarchy, and the vast majority of MFC classes derive from the CObject class. The CObject class contains several basic features that all MFC classes must have: Persistence support, runtime class information support, and diagnostic debugging support. The persistence support feature is provided by the member functions IsSerializable () and serialize (). The former is used to detect whether the object supports serialization. If a class can be serialized, it must include the DECLARE_SERIAL macro at the time of declaration, including the IMPLEMENT_SERIAL macro when implemented. The Serialize () function can write an object to an archive file (Archive) or read an object from an archive file. The member function Getruntimeclass () can get a pointer to a CRuntimeClass class object that provides run-time class information for the object. The CObject class provides member functions AssertValid () and dump () for diagnostic debugging support, which checks the validity of an object's memory state, which dumps the object's contents into a CDumpContext object. and can provide diagnostic services and some useful debugging information.

In MFC, the CWnd class provides the basic functionality of all window classes and is a very important class, with approximately One-third of MFC classes as base classes. This class is mainly to create, manipulate the window class API function encapsulation, and through the message mapping mechanism to hide the SDK programming using the inconvenient window processing function, is the message distribution processing more convenient.

The most important encapsulation of the CWnd class is the encapsulation of the API function CreateWindow (), which is encapsulated as a CWnd class member function, create (). From the VC provided by the MFC source file WinCore.cpp can clearly see the CWnd class to the CreateWindow () function of the encapsulation process, the following gives the relevant part of the implementation of the list:

BOOL cwnd::create (LPCTSTR lpszclassname, LPCTSTR lpszwindowname, DWORD dwstyle, const rect& RECT, cwnd* pParentWnd, UI NT NID, ccreatecontext* pContext)
{
Can ' t use to desktop or pop-up windows (use CreateEx instead)
ASSERT (pParentWnd! = NULL);
ASSERT ((dwstyle & ws_popup) = = 0);
Return CreateEx (0, lpszClassName, lpszWindowName, Dwstyle | Ws_child, Rect.left, Rect.top, Rect.right-rect.left, Rect.bottom-rect.top, Pparentwnd->getsafehwnd (), (HMENU) NID, (LPVOID) pContext);
}


As you can see, the main work is done in the CreateEx () member function, which is the encapsulation of the API function CreateWindowEx (). The encapsulated code constructs and populates a createstruct structure that is very similar to the WNDCLASS structure before calling CreateWindowEx () and calls PreCreateWindow ().

BOOL Cwnd::createex (DWORD dwExStyle, LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwstyle, int x, int y, int nwidt h, int nheight, HWND hwndparent, HMENU nidorhmenu, LPVOID lpparam)
{
Allow modification of several common create parameters
CREATESTRUCT cs;
Cs.dwexstyle = dwExStyle;
Cs.lpszclass = lpszClassName;
Cs.lpszname = lpszWindowName;
Cs.style = dwstyle;
cs.x = x;
Cs.y = y;
cs.cx = nwidth;
Cs.cy = nheight;
Cs.hwndparent = hwndparent;
Cs.hmenu = Nidorhmenu;
Cs.hinstance = AfxGetInstanceHandle ();
Cs.lpcreateparams = Lpparam;
if (! PreCreateWindow (CS))
{
PostNcDestroy ();
return FALSE;
}
Afxhookwindowcreate (this);
HWND hwnd =:: CreateWindowEx (Cs.dwexstyle, Cs.lpszclass, Cs.lpszname, Cs.style, Cs.x, Cs.y, cs.cx, Cs.cy, Cs.hwndParent, C S.hmenu, Cs.hinstance, cs.lpcreateparams);
#ifdef _DEBUG
if (hWnd = = NULL)
{
TRACE1 ("Warning:window creation Failed:getlasterror returns 0x%8.8x\n", GetLastError ());
}
#endif
if (! Afxunhookwindowcreate ())
PostNcDestroy (); Cleanup if CreateWindowEx fails too soon
if (hWnd = = NULL)
return FALSE;
ASSERT (hWnd = = m_hwnd); Should has been set in Send MSG hook
return TRUE;
}


Seemingly encapsulated window creation functions are much more complex than the original API functions, but this does not mean that MFC's encapsulation will result in inefficient programming, and on the contrary, because CWnd appears in the form of a base class in most cases, you can add code completion to CWnd in a derived class: Create () makes it easier to implement the creation of a derived class window.

3 MFC Applications program Frame

The MFC application framework can be thought of as a superset of the MFC base Class library (superset), which is a collection of many classes that can be used in any program, while the application framework defines the structure of the program itself. A simple example using the MFC application framework is given below, which provides a clearer understanding of the general structure of the MFC application framework.

Sample01.h file
Application Classes
Class Csample01app:public CWINAPP
{
Public
Virtual BOOL InitInstance ();
};
frame window class
Class Csample01frame:public CFrameWnd
{
Public
Csample01frame ();
Protected
afx_msg void OnPaint ();
Declare_message_map ()
};
Sample01.cpp file
#include <afxwin.h>
#include "Sample01.h"
Application objects
Csample01app Theapp;
Initializing an application instance
BOOL csample01app::initinstance ()
{
m_pMainWnd = new Csample01frame ();
M_pmainwnd->showwindow (m_nCmdShow);
M_pmainwnd->updatewindow ();
return TRUE;
}
Message map
Begin_message_map (Csample01frame, CFrameWnd)
On_wm_paint ()
End_message_map ()
constructor function
Csample01frame::csample01frame ()
{
Create (NULL, "MFC Application Framework Program");
}
WM_PAINT Message response function
void Csample01frame::onpaint ()
{
CPAINTDC DC (this);
dc. TextOut (+, "Hello world!");
}


Still like writing Sample00 program to establish a WIN32 application engineering SAMPLE01 (see "CD \ Companion program \sample01\"), Then add the header file Sample01.h and the source file Sample01.cpp to the project separately, and write the above code to the appropriate file. In order to be able to compile successfully, you also need to modify the compile command, through the "ALT+F7" shortcut key to the "Project Settings" dialog box, the "Preprocessor Definitions" column to add the last option "_afxdll", preceded by a comma separated. Next you need to add the command line "/MD" at the end of the "Project Options" column, separating the other command line arguments with a space. Compile and run, you can see that the effect is the same as the SAMPLE00 program written in the SDK, but more structured on the implementation of the Code, the writing process is more simple.

Next, the above application framework code is analyzed. Start with the derived class Csample01app of the core--cwinapp class of the MFC application. The CWinApp class provides message loops and some key virtual functions that can get messages and distribute the obtained messages to the application window, and the overloads of these virtual functions allow developers to extend some of the intrinsic behavior of the application. When the head file Afxwin.h is included, you can use some MFC classes, including CWinApp, in your program. An MFC application has and can have only one application object and must be declared globally, so the object resides in memory since the program started running.

Because programs that use the MFC application framework are still Windows applications in nature, there is a need to have the WinMain () function in the program as the portal for Windows applications. The WinMain () function was not seen in the previous example code because the function was hidden in the application framework by means of encapsulation. In addition to WinMain (), the CWinApp class member function run () is also implicitly executed, and this function is also very important, which is responsible for putting the message into the message loop of the application window, which completes the call to run () by the WinMain () function. The virtual function InitInstance () of the CWinApp class is called immediately after the WinMain () function finds the Application object. Because the CWinApp base class does not know exactly what main frame window is required, the InitInstance () function must be overloaded in the derived class of CWinApp when it is used. The InitInstance () function is called when the application is already running but the window has not yet been created, and the application cannot own the window unless the window is created by InitInstance (). This also means that applications that lack the InitInstance () function will not be able to receive and process messages, which is meaningless for Windows programs. Thus, deriving from the CWinApp class and overloading the InitInstance () function are necessary for writing an MFC application Framework program.

In addition to the application class, the Csample01frame class derived from CFrameWnd also describes the main frame window of the application. Calling the CFrameWnd member function of the base class in the constructor, create (), is responsible for creating the actual window structure by Windows and linking it to C + + objects by the application framework.

Most of the functionality of this sample program is actually done in base classes such as MFC's CWinApp and CFrameWnd, where you can programmatically write a small amount of functionality code in a derived class, which allows C + + to borrow a lot of code from a base class without duplicating code. The application framework is responsible for the architecture of the provider, and the developer adds the corresponding implementation code on top of it, making it very easy to complete a complete application. The application framework not only defines the structure of the application, it actually contains more C + + base classes.

   4 Summary

The API programming method of the SDK, MFC programming method and the ATL programming method which will be introduced later in this series is the more commonly used programming method in VC + + programming, in which MFC becomes the most common programming way for most program developers using its powerful function and flexible programming way. This paper discusses MFC and its framework program in detail from the basic problems, so that readers can have a basic understanding of MFC programming.

Transferred from: http://www.cnblogs.com/lidabo/archive/2012/11/23/2785030.html

Getting Started with the MFC Application Framework (GO)

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.