In the past few days I have one question:
In MFC, we create an application ob开发者_运维知识库ject derived from CWinApp
. We create this object globally. So the MFC framework will use this object to start the application.
But I don’t know how the frame work comes to know about my global object.
Please explain me the internal mechanism whereby MFC learns about the application object.
From MSDN:
Each application that uses the Microsoft Foundation classes can only contain one object derived from CWinApp. This object is constructed when other C++ global objects are constructed and is already available when Windows calls the WinMain function, which is supplied by the Microsoft Foundation Class Library. Declare your derived CWinApp object at the global level.
Basically because your CWinApp object is a global variable, by the time the application gets to WinMain it has already instantiated your CWinApp object. And because there can be only one CWinApp object, it knows that this is the one.
After debugging the sample MFC application I learned how the framework knows about the application object.
The application object is global and inherited from CWinApp
. Since the object is global this object is constructed before WinMain
is called. While constructing the derived object the CWinApp
class constructer is called; at this time framework captures the handle:
pModuleState->m_pCurrentWinApp = this;
The above line is copied from the MFC CWinApp::CWinApp(LPCTSTR lpszAppName)
constructor.
If you want further details then go to the definition and declaration of the class CWinApp
.
精彩评论