上一節簡單學習了關於MFC中簡單的層次結構,而MFC程序的初始化過程究竟是怎麼樣的呢,與普通Win32初始化的聯繫又在哪呢?
Win32程序通過RegisterClass,CreateWindow,ShowWindow,UpdateWindow實現對程序的初始化,下面我們來看對MFC初始化的仿真。
*MFC程序的初始化過程
先上類圖:
我們來看main函數:
CMyWinApp theApp;
int _tmain(int argc, _TCHAR* argv[])
{
CWinApp * pApp = AfxGetApp();
pApp->InitApplication();
pApp->InitInstance();
pApp->Run();
system("pause");
return 0;
}
(1)首先產生一個CMyWinApp theApp對象。
(2)進入main函數,因爲在CWinThread中增加了兩個虛函數: InitIstance()和run(),CWinApp中增加了虛函數InitApplication(),虛函數在子類中進行override,實現了類的多態,即main函數CwinApp *pApp中依次調用的函數是:CWinApp::InitApplication(),CMyWinApp::InitInstance(),CWinApp::Run()。
(3)函數進入CWinApp::InitApplication()
(4)函數進入CMyWinApp::InitInstance()
virtual BOOL InitInstance()
{
std::cout << "CMyWinApp::InitInstance \n";
m_pMainWnd = new CMyFrameWnd;
return TRUE;
}
調用CMyFrameWnd的構造函數
CMyFrameWnd()
{
Create();
std::cout << "CMyFrameWnd Constructor \n";
}
此處根據多態性,調用CFrameWnd::Create() (CFrameWnd覆蓋掉了父類CWnd虛函數)BOOL Create()
{
std::cout << "CFrameWnd::Create \n";
CreateEx();
return TRUE;
}
再調用CWnd::CreateEx()
BOOL CreateEx()
{
std::cout << "CWnd::CreateEx \n";
PreCreateWindow();
return TRUE;
}
此處PreCreateWindow()已被CFrameWnd override,此處調用CFrameWnd::PreCreateWindow();[不得不提這也是虛函數的奇妙所在]在此完成CFrameWnd的構造函數,繼而進行CMyFrameWnd的構造函數。
(5)函數進入CWinApp::Run()
virtual void Run()
{
std::cout << "CWinApp::Run \n";
return CWinThread::Run();
}
繼而調用CWinThread::Run()完成整個過程。
下面是運行結果截圖:
我們來回到前面的類圖,執行順序如圖下
整個流程如圖,不得不說在MFC框架仿真中,虛函數是多麼重要。
在以上流程中我們仿真了MFC的初始化過程,但是過程中我們並未見到WinMain()函數,函數消失了嗎?其實並不是,我們來看下面。
如果我新建一個MFC程序,只添加以下幾行代碼:
CMyWinApp theApp;
BOOL CMyWinApp::InitInstance()
{
AfxMessageBox(L"test!");
return TRUE;
}
我們發現程序依然可以 運行,彈窗。的確MFC好像已經將WinMain,消息循環等封裝進了CMyWinApp等的構造之中,這也就是後面會探究學習的地方。