一、观察Frame7的运行原理
void main()
{
CWinApp* pApp = AfxGetApp();
pApp->InitApplication();
pApp->InitInstance();
pApp->Run();
CMyDoc* pMyDoc = new CMyDoc;
CMyView* pMyView = new CMyView;
CFrameWnd* pMyFrame = (CFrameWnd*)pApp->m_pMainWnd;
// output Message Map construction
AFX_MSGMAP* pMessageMap = pMyView->GetMessageMap();
cout << endl << "CMyView Message Map : " << endl;
MsgMapPrinting(pMessageMap);
}
二、MFC基本类图
CObject
CCmdTarget
CWinThread
CWinApp
CMyWinApp
CWnd
CView
CFrameWnd
CDocument
CMyDoc
其他几个可以顾名思义,先看看CCmdTarget:
CCmdTarget is the base class for the Microsoft Foundation Class Library message-map architecture. A message map routes commands or messages to the member functions you write to handle them. (A command is a message from a menu item, command button, or accelerator key.)
Key framework classes derived from CCmdTarget include CView, CWinApp, CDocument, CWnd, and CFrameWnd. If you intend for a new class to handle messages, derive the class from one of these CCmdTarget-derived classes. You will rarely derive a class from CCmdTarget directly.
三、AfxGetApp()的模拟
Frame7采用的是全局函数。
实际中,不是这么简单:
Afxwin1.inl
// Global helper functions
1, _AFXWIN_INLINE CWinApp* AFXAPI AfxGetApp()
{ return afxCurrentWinApp; }
2, #define afxCurrentWinApp AfxGetModuleState()->m_pCurrentWinApp
3, AFX_MODULE_STATE* AFXAPI AfxGetModuleState()
{
_AFX_THREAD_STATE* pState = _afxThreadState;
AFX_MODULE_STATE* pResult;
if (pState->m_pModuleState != NULL)
{
// thread state's module state serves as override
pResult = pState->m_pModuleState;
}
else
{
// otherwise, use global app state
pResult = _afxBaseModuleState.GetData();
}
ASSERT(pResult != NULL);
return pResult;
}
另外,实际的初始化也不是简单的:
CWinApp* pApp = AfxGetApp();
pApp->InitApplication();
pApp->InitInstance();
pApp->Run();
四、AFX_MSGMAP* pMessageMap = pMyView->GetMessageMap();
GetMessageMap分别在两个宏里面声明和定义:
#define DECLARE_MESSAGE_MAP() /
static AFX_MSGMAP_ENTRY _messageEntries[]; /
static AFX_MSGMAP messageMap; /
virtual AFX_MSGMAP* GetMessageMap() const;
#define BEGIN_MESSAGE_MAP(theClass, baseClass) /
AFX_MSGMAP* theClass::GetMessageMap() const /
{ return &theClass::messageMap; } /
AFX_MSGMAP theClass::messageMap = /
{ &(baseClass::messageMap), /
(AFX_MSGMAP_ENTRY*)(theClass::_messageEntries) }; /*此处的取地址&真奇妙*//
AFX_MSGMAP_ENTRY theClass::_messageEntries[] = /
{
展开后:
// in implementation file
AFX_MSGMAP* CView::GetMessageMap() const
{ return &CView::messageMap; }
//自己messageMap的定义,
AFX_MSGMAP CView::messageMap =
{
&(CWnd::messageMap), // 第一个字段,父类的messageMap指针。
(AFX_MSGMAP_ENTRY*) &(CView::_messageEntries) //第二个字段自己实体数组的指针。
};