|
[笔记]《明明白白看MFC之程序框架(二)》
二、 MFC应用程序结构
借助向导,可以快速的生成一个SDI的Windows应用程序。在使用向导生成应用程序后,会发现有好几个文件, 其主要代码如下:
CHelloWorldApp theApp;
int AFXAPI AfxWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow)
{
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:
……………………
AfxWinTerm();
return nReturnCode;
}
BOOL CWinApp::InitApplication()
{
if (CDocManager::pStaticDocManager != NULL)
{
if (m_pDocManager == NULL)
m_pDocManager = CDocManager::pStaticDocManager;
CDocManager::pStaticDocManager = NULL;
}
if (m_pDocManager != NULL)
m_pDocManager->AddDocTemplate(NULL);
else
CDocManager::bStaticInit = FALSE;
return TRUE;
}
BOOL CHelloWorldApp::InitInstance()
{
AfxEnableControlContainer();
………………………………
// Change the registry key under which our settings are stored.
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization.
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
LoadStdProfileSettings(); // Load standard INI file options (including MRU)
// Register the application's document templates. Document templates
// serve as the connection between documents, frame windows and views.
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS(CHelloWorldDoc),
RUNTIME_CLASS(CMainFrame), // main SDI frame window
RUNTIME_CLASS(CHelloWorldView));
AddDocTemplate(pDocTemplate);
// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// Dispatch commands specified on the command line
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// The one and only window has been initialized, so show and update it.
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
return TRUE;
}
BOOL CWinApp::InitInstance()
{
return TRUE;
}
MFC应用程序之“Hello World”
咋一眼看上去,好像这个程序无从下手分析,甚至连程序的入口点都找不到。其实,上面的程序还是经过整理后才有如此模样,刚刚入门的我就花了不少功夫才整理出上面的运行脉络,已经较清晰了^_^
在程序的开始处,首先定义了一个全局变量theApp,他代表了整个程序的存在,然后程序开始进入入口点。但是,这里的入口点不再是C的main()或者是SDK中的WinMain()了,起而代之的是AfxWinMain(),如果不去深究 为什么,那么就当成是第一次到C语言中的main()函数一样,只要知道程序从这里开始执行就可以了!实际上,在AfxWinMain()中为了驱动程序的执行,调用了好几个函数,执行路径为:入口点----〉AfxGetThread()------〉AfxGetApp()------- |
|