學MFC,竟然還不知道MFC的MAIN函數在什麼地方?怎麼啟動並執行?實在不高明。於是決定模仿JJHOU老師的方式,拿起手術刀,深入MFC的內部運行機制。但是俗話說,循序漸進。就是說在我們深入之前,首先要淺析一下… …
假如你用AppWizard一步一步NEXT下來,然後在CLASSVIEW中去找尋WINMAIN函數,那麼你只有失望。MFC最大的特點是什嗎?封裝!MFC的確封裝的太好了,以至於很多想學習MFC的人都望而卻步。閑話少說,還是繼續我們今天的話題,MAIN函數!實話告訴你吧,即使你搜尋所有的MFC產生的檔案,都無法發現WINMAIN的字眼,那麼它就近在什麼地方呢?
我相信你已經想到,MAIN函數應該在主要的應用程式檔案中。難道是“您定義的程式名.cpp”這個檔案?不錯就是它。再Crtl+F一下,看有沒有我們要找的WINMAIN函數?看來你又要失望了,但是你主意有這樣一句:
/////////////////////////////////////////////////////////////////////////////
// The one and only CMy1App object
CMy1App
theApp; //本人建立的工程名為1。
是不是很特別,再注意一下那句注釋“The one and only CMy1App object”,每個應用程式有且只用一個CMy1App對象。我想你應該想到了,WinMain函數每個程式也只能有一個,那麼這個全域對象跟WinMain函數肯定有莫大的關係?沒錯,相信你的直覺。
現在,我們該深入WinMain運行機制了。
首先,看看MFC的庫檔案把,它能給我們帶來許多驚喜。(vc6的相應的目錄是/Microsoft Visual Studio/VC98/MFC/SRC;VC7相應的目錄是/Microsoft
Visual Studio .NET 2003/Vc7/atlmfc/src/mfc)
首先應該看看CMy1App的基類,CWinApp的建構函式(在APPCORE.CPP中),找到以下內容:
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,就到這裡就可以了。現在請注意:
pModuleState->m_pCurrentWinApp
= this;
這段代碼的意思是,獲得了CWinApp的全域對象的this指標。CWinApp之中的成員變數將因為theApp這個全域對象的誕生而獲得配置和初始值。theApp配置完成以後,接下來就是今天的主角兒了,WinMain函數,開啟appmodul.cpp:
_tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow)
{
// call shared/exported WinMain
return AfxWinMain(hInstance,
hPrevInstance, lpCmdLine, nCmdShow);
}
然後再開啟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)
{
TRACE(traceAppMsg,0,"Warning:Destroying
non-NULL m_pMainWnd/n");
pThread->m_pMainWnd->DestroyWindow();
}
nReturnCode
= pThread->ExitInstance();
goto
InitFailure;
}
終於看到WinMain的真面目了,但是我們並不能滿足,接下來,我們要瞭解他的運行機制,我們要知其然,更要知其所以然。只知其然,實在不高明!