MFC实例分析

实例HelloWord.cpp 首先创建一个CHelloWordApp theApp类型的全局变量;调用完CHelloWordApp 和CWinAppEx以及CWinApp的构造函数以后进入
extern “C” int WINAPI
_tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
In LPTSTR lpCmdLine, int nCmdShow)
#pragma warning(suppress: 4985)
{
// call shared/exported WinMain
return AfxWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
}
在TCHAR.h中,有此定义:#define _tWinMain WinMain,所以这里的_tWinMain就是WinMain函数。它调用了AfxWinMain函数(位于WinMain.cpp中)。
在_tWinMain调用了AfxWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow),
在AfxWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow)
{
// App global initializations (rare)
CWinThread* pThread = AfxGetThread();//得到当前应用程序指针
CWinApp* pApp = AfxGetApp();//AfxGetApp()返回的是应用程序对象theApp的指针.

if (pApp != NULL && !pApp->InitApplication())
	goto InitFailure;
if (!pThread->InitInstance())//访问到HelloWord程序中的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();

}

MFC里AfxGetThread()与AfxGetAPP()的区别
复制代码
1 CWinThread* AFXAPI AfxGetThread()
2 {
3 // check for current thread in module thread state
4 AFX_MODULE_THREAD_STATE* pState = AfxGetModuleThreadState();
5 CWinThread* pThread = pState->m_pCurrentWinThread;
6
7 // if no CWinThread for the module, then use the global app
8 if (pThread == NULL)
9 pThread = AfxGetApp();
10
11 return pThread;
12 }
复制代码
复制代码
1 _AFXWIN_INLINE CWinApp* AFXAPI AfxGetApp()
2 {
3 return afxCurrentWinapp;
4 }
5 //在AFXWIN.H中 #define afxCurrentWinApp AfxGetModuleState()->m_pCurrentWinApp
6 //AfxGetModuleState()就是得到当前模块,AfxGetModuleState()->m_pCurrentWinApp=this;得到当前应用程序的对象指针
复制代码
AfxGetThread()返回的是当前界面线程对象的指针,AfxGetApp()返回的是应用程序对象theApp的指针.

如果该应用程序(或进程)只有一个界面线程在运行,那么这两者返回的都是一个全局的应用程序对象theApp的指针。

如果在多线程时调用AfxGetThread返回的与AfxGetApp并不一定相同。

猜你喜欢

转载自blog.csdn.net/weixin_37603532/article/details/89512648
MFC