MFC Program Running Mechanism

Source: Internet
Author: User
I still don't know where the MAIN function of MFC is? How to run it? It's really not brilliant.
I have been familiar with JJHOU's in-depth introduction to MFC. Haha, this article is intended for friends who have never read that book but want to learn about MFC programming. (Friends who haven't read the book are not buying it now ?) In fact, this article is mainly a summary and supplement to Chapter 6 of "getting down to MFC! (This article has some opinions on the different parts of this book !)
Let's get down to the truth.
If you use AppWizard to step by step NEXT and then look for the WINMAIN function in CLASSVIEW, you will be disappointed. What are the biggest characteristics of MFC? Encapsulation! The MFC package is so good that many people who want to learn it are discouraged. Let's talk less about it. Let's continue with our topic today, the MAIN function! To tell you the truth, even if you search for all the files generated by MFC, you cannot find the word WINMAIN. So where is it nearby?
I believe you have come up with the idea that the MAIN function should be in the MAIN application file. Is it the file "Your defined program name. cpp? That's it. Crtl + F again. Can you see the WINMAIN function we are looking? You may be disappointed again, but note the following:

//////////////////////////////////////// /////////////////////////////////////
// The one and only CMyApp object

CMyApp theApp; // The project name I created is My.

Isn't it special? Pay attention to The comment "The one and only CMyApp object". Each application has only one CMyApp object. I think you should have thought that each program of the WinMain function can only have one. Is there a great relationship between this global object and the WinMain function? That's right. Trust your intuition.
Note: those who know the details of C ++ must know that the global object takes precedence over the execution of the MAIN function. If you do not know, it doesn't matter. I will tell you here: "global objects take precedence over MIAN function execution and are built on stacks. Remember, remember !"
Now, we should go deep into the WinMain operating mechanism. Specifically, it should be the MFC mechanism!
First, let's take a look at the library file of MFC, which can bring us many surprises. (The corresponding directory of vc6 is \ Microsoft Visual Studio \ VC98 \ MFC \ SRC; the corresponding directory of VC7 is \ Microsoft Visual Studio. NET 2003 \ Vc7 \ atlmfc \ src \ mfc)
Now let's start from this global journey.
CMyApp theApp;
In this case, the system executes the CWinApp constructor of the CMyApp parent class, and then executes the constructor of the CMyApp. (You have a father and a son first !), The CWinApp constructor is called.

CWinApp Constructor (in the MFC Code provided by VC, query keywords in the form of a word or phrase in the text, and open APPCORE. CPP. The following uses the same search method and does not repeat it .) Find the following content:
CWinApp: CWinApp (LPCTSTR lpszAppName)
{
If (lpszAppName! = NULL)
M_pszAppName = _ tcsdup (lpszAppName );
Else
M_pszAppName = NULL;

// Initialize CWinThread state
AFX_MODULE_STATE * pModuleState = _ AFX_CMDTARGET_GETSTATE ();
AFX_MODULE_THREAD_STATE * pThreadState = pModuleState-> m_thread;
ASSERT (AfxGetThread () = NULL );
PThreadState-> m_pCurrentWinThread = this;
ASSERT (AfxGetThread () = this );
M_hThread =: GetCurrentThread ();
M_nThreadID =: GetCurrentThreadId ();

// Initialize CWinApp state
ASSERT (afxCurrentWinApp = NULL); // only one CWinApp object please
PModuleState-> m_pCurrentWinApp = this;
ASSERT (AfxGetApp () = this );
......
}
OK, you can do it here. Take a closer look at the code above. It has completed the startup of the thread amount of the application, and it has given the life of our program. Note:
PThreadState-> m_pCurrentWinThread = this;
PModuleState-> m_pCurrentWinApp = this;
These two lines of code are actually one thing to do.
This Code indicates that this pointer is obtained for the Global Object of CMyApp. (Why is it the pointer of CMyApp? This is currently in CWinApp? My answer is, but you are the CWinApp construction caused by the CMyApp object !!) This pointer is not an ordinary character. We will rely on it to do a lot of work later.
The member variables in CWinApp get the configuration and initial values because theApp is a global object.
After the parent class is constructed, the Child class is constructed. But we can see that AppWizard does not do anything in our subclass? Yes, it's all yours!
CMyApp: CMyApp ()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}

Next is the main role of today. Search for the keyword "WinMain" and many files will appear. Don't worry, because now we should first look at the WinMain statement. Open appmodul. cpp:

_ TWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow)
{
// Call shared/exported WinMain
Return AfxWinMain (hInstance, hPrevInstance, lpCmdLine, nCmdShow );
}

Here _ tWinMain is a macro named to support UNICODE. What really works is AfxWinMain. Check whether its parameters are the same as the WinMain function of the SDK?
Search for afxwinmain again, which is actually in winmain. cpp:

Int afxapi afxwinmain (hinstance, hinstance hprevinstance,
Lptstr lpcmdline, int ncmdshow)
{
Assert (hprevinstance = NULL );

Int nreturncode =-1;
Cwinthread * pthread = afxgetthread ();
Cwinapp * PAPP = afxgetapp ();

// Afx internal Initialization
If (! Afxwininit (hinstance, hprevinstance, lpcmdline, ncmdshow ))
Goto initfailure;

// App global initializations (rare)
If (PAPP! = NULL &&! PAPP-> initapplication ())
Goto initfailure;

// Perform specific initializations
If (! Pthread-> initinstance ())
{
If (pthread-> m_pmainwnd! = NULL)
{
Trace (traceappmsg, 0, "Warning: destroying non-null m_pmainwnd \ n ");
PThread-> m_pMainWnd-> DestroyWindow ();
}
NReturnCode = pThread-> ExitInstance ();
Goto InitFailure;
}
NReturnCode = pThread-> Run ();
......
}
Pay attention to five details for this code segment:
CWinApp * pApp = AfxGetApp ();
THIS is the object pointer. Don't remember? The one pointing to the CMyApp! It is worth noting that Afx is global and can be called at any time. (AFX is the development code of the MFC Development Team. It means that Application Framework legend X is only for good looks, doesn't it really mean ?!)
If (! AfxWinInit (hInstance, hPrevInstance, lpCmdLine, nCmdShow ))
AfxWinInit completes thread initialization and window class registration. For more information, see the definition in appinit. cpp.
If (pApp! = NULL &&! PApp-> InitApplication ())
In fact, pApp and pThread are the same pointer and both are pointers to CMyApp. Here, because InitApplication is not defined in CMyApp, CWinApp: InitApplication () is actually called (), completed Content Management of MFC.
If (! PThread-> InitInstance ())
Because it is rewritten in CMyApp, calling it in CMyApp is actually initialization. The definition of the default window class is also completed. If you are familiar with SDK programming, you will not forget the steps for designing, registering, creating, implementing, and updating window classes. At this time, MFC thinks that you have designed the default window class.
Now you can't help wondering, what is the difference between InitApplication () and InitInstance?
The answer is: If you execute a program, both functions will be called. If you do not close the previous program, execute another program, then only the last function is executed.
NReturnCode = pThread-> Run ();
This step has become the active source of the program in "getting down to MFC". In my opinion, it is the step for you to drive on the accelerator. We will elaborate on it later!

After the design window class, it should be the registration. MFC automatically calls (jumps to) AfxEndDeferRegisterClass (WINCORE. CPP). Five window classes are registered for you: AfxWnd, AfxCreateBar, AfxMDIFrame, AfxFrameOrView, and AfxOleControl. The above window class MFC will be automatically converted into independent class names without two, for calling.
After the window is registered, it should be the creation of the window. At this time, CFrameWnd: Create () will be called. The code is located in WINFRM. Cpp.
BOOL CFrameWnd: Create (LPCTSTR lpszClassName,
LPCTSTR lpszWindowName,
DWORD dwStyle,
Const RECT & rect,
CWnd * pParentWnd,
LPCTSTR lpszMenuName,
DWORD dwExStyle,
CCreateContext * pContext)
{
Hmenu = NULL;
If (lpszmenuname! = NULL)
{
// Load in a menu that will get destroyed when window gets destroyed
Hinstance hinst = afxfindresourcehandle (lpszmenuname, rt_menu );
If (hmenu =: loadmenu (hinst, lpszmenuname) = NULL)
{
Trace (traceappmsg, 0, "Warning: failed to load menu for cframewnd. \ n ");
Postncdestroy (); // perhaps Delete the C ++ object
Return false;
}
}

M_strtitle = lpszwindowname; // save title for later

If (! Createex (dwexstyle, lpszclassname, lpszwindowname, dwstyle,
Rect. Left, rect. Top, rect. Right-rect. Left, rect. Bottom-rect. Top,
Pparentwnd-> getsafehwnd (), hmenu, (lpvoid) pcontext ))
{
Trace (traceappmsg, 0, "Warning: failed to create cframewnd. \ n ");
If (hmenu! = NULL)
Destroymenu (hmenu );
Return false;
}

Return true;
}

The window creation is completed, and the extended calling createex is also involved. For details, see msdn.

At this point, you can't help but ask, are we all finished with MFC? The windows for industrial production are all the same. I want to have my own style!
Don't worry, MFC provides users with an opportunity to modify the window design, that is, precreatewindow (createstruct & Cs). You can query the createstruct struct in msdn, you will find that it is almost the same as our createwindow. This is an opportunity for MFC to change the window. During precreatewindow, it will jump to cwnd: precreatewindow, which contains a macro: afxdeferregisterclass. Its function is: if the window class is not registered, it will be registered; if it is registered, no matter what it is!
The design, registration, and creation of window classes have been completed, and only updates and displays are available. These tasks are completed by cmyapp: initinstance:
M_pmainwnd-> showwindow (sw_show );
M_pmainwnd-> updatewindow ();
Now if (! Pthread-> initinstance () has been completed. According to the content of the main function, next this: nreturncode = pthread-> Run ()
In this case, the run () function of cmyapp should be called, but in the cmyapp class, such a function is not declared or defined at all. According to the original polymorphism, the pointer is promoted to cwinapp :: run (), whose code is located in appcore. CPP:

Int CWinApp: Run ()
{
If (m_pMainWnd = NULL & AfxOleGetUserCtrl ())
{
// Not launched/Embedding or/Automation, but has no main window!
TRACE (traceAppMsg, 0, "Warning: m_pMainWnd is NULL in CWinApp: Run-quitting application. \ n ");
AfxPostQuitMessage (0 );
}
Return CWinThread: Run ();
}

Finally, you will find that it calls a CWinThread: Run (), and you will not be able to see the CWinThread: Run () Code (at least I did not find it, because Microsoft only provides part of the MFC code .) However, you can find the CWinThread: Run () Description in MSDN:
The Run function that controls the thread. Contains the message pump. Generally, this parameter is not rewritten.
The specific points are:
Run acquires and dispatches Windows messages until the application Generated es a WM_QUIT message. if the thread's message queue currently contains no messages, Run callonidle to perform idle-time processing. incoming messages go to the PreTranslateMessage member function for special processing and then to the Windows function TranslateMessage for standard keyboard translation. finally, the DispatchMessage Windows function is called.
Run is rarely overridden, but you can override it to implement special behavior.
This member function is used only in user-interface threads.
It originally wrapped the message loop and called message map in MFC!

Haowen

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.