MFC封裝WINDOWS應用程式的流程

來源:互聯網
上載者:User

MFC封裝了WIN API.大家都知道.但是MFC應用程式的真正流程又有多少人知道呢?

下面就是我對MFC啟動代碼的一些剖析.

在TCHAR.H裡,有這麼2小段define.通過我的簡化,我們可以看到:

//TCHAR.H
#ifdef _UNICODE
#define _tWinMain wWinMain
#else
#define _tWinMain WinMain
#endif

由於為了支援UNICODE,C運行庫對WinMain其實區分了UNICODE版和ANSI版.對UNICODE版的程式,C運行庫將調用wWinMain,而對於ANSI版的應用,則調用WinMain.這是第一點.

然後,其實MFC的代碼設計時是自動支援UNICODE的,所以,MFC的WinMain在APPMODUL.CPP被定義為

_tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)

這樣以一來,無論使用者#define _UNICODE與否,MFC的WinMain都會被調用.接下來,_tWinMain的實際運作如下:

extern "C" int WINAPI
_tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow)
{
// call shared/exported WinMain
return AfxWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
}

這樣,AfxWinMain就和MFC掛上了鉤.甚至在PETER NORTON的書中,都僅講到了AfxWinMain乃是MFC的WinMain,但是,NORTON同志看來沒有講述清楚這點.因為,WinMain仍然是WinMain,C運行庫並沒有因為MFC的存在而重新設計AfxWinMain的入口.

在MS的AfxWinMain(WINMAIN.CPP)裡我們可以看到如下代碼:

int AFXAPI AfxWinMain(HINSTANCE 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 calls
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;
}

以上代碼將整個龐大的MFC架構完全啟動起來.如果要瞭解其Afx大頭的函數群,大家可以對以看一下MFC原始碼裡的*CORE.CPP.

真正的痛點到是到TCHAR.H中找到WinMain的別名吧.因為幾乎沒人會想到TCHAR.H居然隱藏了如此大的MFC機要啊...

現在,MFC的啟動流程就完全清楚了吧...:)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.