MFC encapsulates win api. Everyone knows. But how many people know the real process of the MFC application?
The following is my analysis of the MFC startup code.
In tchar. h, there are two short segments define. Through my simplification, we can see:
// Tchar. h
# Ifdef _ Unicode
# DEFINE _ twinmain wwinmain
# Else
# DEFINE _ twinmain winmain
# Endif
To support Unicode, the C Runtime actually distinguishes Unicode and ANSI versions from winmain. for Unicode programs, the C Runtime Library calls wwinmain, while for ANSI applications, it calls winmain. this is the first point.
Then, in fact, the code of MFC is designed to automatically support Unicode. Therefore, the winmain of MFC is defined
_ Twinmain (hinstance, hinstance hprevinstance, lptstr lpcmdline, int ncmdshow)
In this way, no matter whether the user # DEFINE _ Unicode or not, the MFC winmain will be called. Next, the actual operation of _ twinmain is as follows:
Extern "C" int winapi
_ Twinmain (hinstance, hinstance hprevinstance,
Lptstr lpcmdline, int ncmdshow)
{
// Call shared/exported winmain
Return afxwinmain (hinstance, hprevinstance, lpcmdline, ncmdshow );
}
In this way, afxwinmain and MFC are hooked up. even in Peter Norton's book, only afxwinmain is the winmain of MFC. However, Comrade Norton did not seem to have clearly stated this. because, winmain is still winmain, and the c Runtime Library does not re-design the afxwinmain portal because of the existence of MFC.
In afxwinmain (winmain. cpp) of MS, we can see the following code:
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)
{
Trace0 ("Warning: destroying non-null m_pmainwnd/N ");
Pthread-> m_pmainwnd-> destroywindow ();
}
Nreturncode = pthread-> exitinstance ();
Goto initfailure;
}
Nreturncode = pthread-> Run ();
Initfailure:
# Ifdef _ debug
// Check for missing afxlocktempmap CILS
If (afxgetmodulethreadstate ()-> m_ntempmaplock! = 0)
{
Trace1 ("Warning: temp map lock count non-zero (% LD)./N ",
Afxgetmodulethreadstate ()-> m_ntempmaplock );
}
Afxlocktempmaps ();
Afxunlocktempmaps (-1 );
# Endif
Afxwinterm ();
Return nreturncode;
}