MFC程序的执行流程为,首先创建一个名为test的MFC工程则在源文件目录会产生一个test.cpp文件。在test.cpp中CtestApp类会产生一个theApp的全局对象。首先要明白,在程序执行main函数之前会先生成全局对象,并执该类的构造函数。则MFC程序的开始为生成theApp全局对象,然后程序继续执行进入main函数。MFC的main函数在appmodul.cpp文件当中为:
tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine, int nCmdShow)
#pragma warning(suppress: 4985)
{
// call shared/exported WinMain
return AfxWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
}
程序会进入tWinMain,转而执行AfxWinMain。AfxWinMain函数在文件winmain.cpp当中,如下所示:
int AFXAPI AfxWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
_In_ 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;
}
nReturnCode = pThread->Run();
InitFailure:
#ifdef _DEBUG
// Check for missing AfxLockTempMap calls
if (AfxGetModuleThreadState()->m_nTempMapLock != 0)
{
TRACE(traceAppMsg, 0, "Warning: Temp map lock count non-zero (%ld).\n",
AfxGetModuleThreadState()->m_nTempMapLock);
}
AfxLockTempMaps();
AfxUnlockTempMaps(-1);
#endif
AfxWinTerm();
return nReturnCode;
}
程序将会进入AfxWinMain函数然后继续执行。再次强调一下MFC执行的过程为:注册窗口,产生窗口,更新窗口,消息循环。执行到!pThread->InitInstance()程序将会转到test.cpp中执行BOOL CtestApp::InitInstance()函数。如果建立的是单文档工程则进入wincore.cpp中的BOOL AFXAPI AfxEndDeferRegisterClass(LONG fToRegister)函数中注册窗口类。但是通常情况下是进入BOOL CtestApp::InitInstance()函数之后执行到if (!ProcessShellCommand(cmdInfo))后进入MainFrm.cpp中执行BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)然后程序跳转进入wincore.cpp中执行BOOL CWnd::PreCreateWindow(CREATESTRUCT& cs)时注册窗口,注册窗口过程也是进入wincore.cpp中的BOOL AFXAPI AfxEndDeferRegisterClass(LONG fToRegister)函数中注册窗口类。注册完窗口类之后紧接着就应该产生窗口,程序进入winfrm.cpp中执行BOOL CFrameWnd::Create然后进入wincore.cpp执行BOOL CWnd::CreateEx产生窗口。产生完窗口之后进入test.cpp中执行m_pMainWnd->ShowWindow(SW_SHOW)显示窗口,然后执行m_pMainWnd->UpdateWindow()更新窗口。窗口创建完成之后程序返回AfxWinMain当中继续执行直到 nReturnCode = pThread->Run()进行消息循环。整个MFC程序执行流程结束。