您的位置:首页 > 其它

MFC 全接触 (一)

2004-08-04 01:59 204 查看
以前对于MFC的了解十分肤浅,只知道MFC = Microsoft Foundation Class,后来还道听途说了很多关于她的风流韵事。有人说她如维纳斯一般美丽,也有人说她和犹大一般丑恶。现在为了手头上的事情,我要从新认识这位也许风华不在的女子了,不管她长得如何,我都得去揭开她那对于我来说神秘的面纱。
还是从打招呼开始吧,以免把她吓着了。于是,我战战兢兢的跟MFC say hello[1]了。
MyApp.h:

class CMyApp : public CWinApp

// frame window class
class CMyFrame : public CFrameWnd
#include <afxwin.h> // MFC library header file declares base classes
#include "myapp.h"

CMyApp theApp; // the one and only CMyApp object

BOOL CMyApp::InitInstance()

BEGIN_MESSAGE_MAP(CMyFrame, CFrameWnd)
ON_WM_PAINT()
END_MESSAGE_MAP()

CMyFrame::CMyFrame()

void CMyFrame::OnPaint()
extern "C" int WINAPI
_tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow)
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 ");
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). ",
AfxGetModuleThreadState()->m_nTempMapLock);
}
AfxLockTempMaps();
AfxUnlockTempMaps(-1);
#endif

AfxWinTerm();
return nReturnCode;
}
在AfxWinMain方法中,
首先,通过调用AfxGetThread方法获得一个CWinThread的类指针。继续step into 到AfxGetThread方法,可以看到该方法包含了获取当前进程指针的语句,如果得到的进程指针为空的话,则调用AfxGetApp以返回一个CWinThread的类指针。当执行了获取当前进程指针的语句后,可以发现返回的CWinThread类指针对应的类为CMyApp;
接着,通过调用AfxGetApp()获得一个CWinApp的类指针。我们可以发现pThread和pApp这两个指针对应着相同的地址,即都是CMyApp类指针对应的类亦为CMyApp;
在调用了两个MFC本身提供的初始化方法之后,调用了在CMyApp中实现的InitInstance方法;紧跟着就是一个十分重要的方法了—— Run。step into到Run方法,我们可以看到Run方法中包含了一个无限的循环,在这个循环当中,不断的从消息队列中获取消息并分发消息,直到获取的消息为退出(WM_QUIT)的时候才终止。
调试花了不少的时间,机子还宕掉了一回,这下总算约莫看见了MFC的背影了,让我们下次再续吧。

Reference: [1] 源代码摘自Programming Microsoft Visual C++ (Fifth Edtion),略有更改。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: