VC----MFC 消息映射机制剖析

MFC的类非常多,继承关系复杂,如何完成MFC巨大的类层次之间消息的传递是一个技术难点,最简单的就是采用虚函数机制,每继承一个类,就覆盖父类的函数,但问题来了,MFC有上百个类,如果使用虚函数,那么每个派生类都会生成一个巨大的虚函数表,效率低下,内存使用率高,违背了微软设计MFC的准则。微软采用了所谓的消息映射机制,来完成不同对象之间消息的传递,本文就MFC9.0源码进行分析,大致讲解MFC的消息映射机制。

步入正题,在AfxWinMain() 函数中,当MFC框架初始化完成后,即 pThread->InitInstance() 执行完成,就开始进行消息循环,入口函数是pThread->Run():

[cpp]  view plain  copy
  1. // Perform specific initializations  
  2. if (!pThread->InitInstance())// MFC初始化框架  
  3. {  
  4.     if (pThread->m_pMainWnd != NULL)  
  5.     {  
  6.         TRACE(traceAppMsg, 0, "Warning: Destroying non-NULL m_pMainWnd\n");  
  7.         pThread->m_pMainWnd->DestroyWindow();  
  8.     }  
  9.     nReturnCode = pThread->ExitInstance();  
  10.     goto InitFailure;  
  11. }  
  12. nReturnCode = pThread->Run();// 进入消息循环  


执行CWinApp:: Run():

[cpp]  view plain  copy
  1. // Main running routine until application exits  
  2. int CWinApp::Run()  
  3. {  
  4.     if (m_pMainWnd == NULL && AfxOleGetUserCtrl())  
  5.     {  
  6.         // Not launched /Embedding or /Automation, but has no main window!  
  7.         TRACE(traceAppMsg, 0, "Warning: m_pMainWnd is NULL in CWinApp::Run - quitting application.\n");  
  8.         AfxPostQuitMessage(0);  
  9.     }  
  10.     return CWinThread::Run();  
  11. }  

执行CWinThread::Run():

[cpp]  view plain  copy
  1. // main running routine until thread exits  
  2. int CWinThread::Run()  
  3. {  
  4.     ASSERT_VALID(this);  
  5.     _AFX_THREAD_STATE* pState = AfxGetThreadState();  
  6.   
  7.     // for tracking the idle time state  
  8.     BOOL bIdle = TRUE;  
  9.     LONG lIdleCount = 0;  
  10.   
  11.     // acquire and dispatch messages until a WM_QUIT message is received.  
  12.     for (;;)  
  13.     {  
  14.         // phase1: check to see if we can do idle work  
  15.         while (bIdle &&  
  16.             !::PeekMessage(&(pState->m_msgCur), NULL, NULL, NULL, PM_NOREMOVE))  
  17.         {  
  18.             // call OnIdle while in bIdle state  
  19.             if (!OnIdle(lIdleCount++))  
  20.                 bIdle = FALSE; // assume "no idle" state  
  21.         }  
  22.   
  23.         // phase2: pump messages while available  
  24.         do  
  25.         {  
  26.             // pump message, but quit on WM_QUIT  
  27.             if (!PumpMessage())  
  28.                 return ExitInstance();  
  29.   
  30.             // reset "no idle" state after pumping "normal" message  
  31.             //if (IsIdleMessage(&m_msgCur))  
  32.             if (IsIdleMessage(&(pState->m_msgCur)))  
  33.             {  
  34.                 bIdle = TRUE;  
  35.                 lIdleCount = 0;  
  36.             }  
  37.   
  38.         } while (::PeekMessage(&(pState->m_msgCur), NULL, NULL, NULL, PM_NOREMOVE));  
  39.     }  
  40. }  

在 do-while 循环中进行消息的路由,主要函数就是 PumpMessage(),我们跟着进入这个函数看看做了什么:

[cpp]  view plain  copy
  1. BOOL CWinThread::PumpMessage()  
  2. {  
  3.   return AfxInternalPumpMessage();  
  4. }  


继续跟踪:
[cpp]  view plain  copy
  1. BOOL AFXAPI AfxInternalPumpMessage()  
  2. {  
  3.     _AFX_THREAD_STATE *pState = AfxGetThreadState();  
  4.   
  5.     if (!::GetMessage(&(pState->m_msgCur), NULL, NULL, NULL))// 从消息队列获取消息  
  6.     {  
  7. #ifdef _DEBUG  
  8.         TRACE(traceAppMsg, 1, "CWinThread::PumpMessage - Received WM_QUIT.\n");  
  9.             pState->m_nDisablePumpCount++; // application must die  
  10. #endif  
  11.         // Note: prevents calling message loop things in 'ExitInstance'  
  12.         // will never be decremented  
  13.         return FALSE;  
  14.     }  
  15.   
  16. #ifdef _DEBUG  
  17.   if (pState->m_nDisablePumpCount != 0)  
  18.     {  
  19.       TRACE(traceAppMsg, 0, "Error: CWinThread::PumpMessage called when not permitted.\n");  
  20.       ASSERT(FALSE);  
  21.     }  
  22. #endif  
  23.   
  24. #ifdef _DEBUG  
  25.     _AfxTraceMsg(_T("PumpMessage"), &(pState->m_msgCur));  
  26. #endif  
  27.   
  28.   // process this message  
  29.   
  30.     if (pState->m_msgCur.message != WM_KICKIDLE && !AfxPreTranslateMessage(&(pState->m_msgCur)))  
  31.     {  
  32.         ::TranslateMessage(&(pState->m_msgCur));  
  33.         ::DispatchMessage(&(pState->m_msgCur));  
  34.     }  
  35.   return TRUE;  
  36. }  

从上面的代码我们可以看到 MFC是通过 GetMessage() 来获取消息,然后再看下面这几句代码:

[cpp]  view plain  copy
  1. if (pState->m_msgCur.message != WM_KICKIDLE && !AfxPreTranslateMessage(&(pState->m_msgCur)))  
  2. {  
  3.     ::TranslateMessage(&(pState->m_msgCur));  
  4.     ::DispatchMessage(&(pState->m_msgCur));  
  5. }  

也就是说当系统获取消息后,先调用 AfxPreTranslateMessage() 这个看起来跟我们经常看到的PreTranslateMessage() 很像!我们来看看到底发生了什么:

[cpp]  view plain  copy
  1. BOOL __cdecl AfxPreTranslateMessage(MSG* pMsg)  
  2. {  
  3.   CWinThread *pThread = AfxGetThread();  
  4.   if( pThread )  
  5.     return pThread->PreTranslateMessage( pMsg );  
  6.   else  
  7.     return AfxInternalPreTranslateMessage( pMsg );  
  8. }  
执行  pThread->PreTranslateMessage():

[cpp]  view plain  copy
  1. BOOL CWinThread::PreTranslateMessage(MSG* pMsg)  
  2. {  
  3.     ASSERT_VALID(this);  
  4.     return AfxInternalPreTranslateMessage( pMsg );  
  5. }  

执行AfxInternalPreTranslateMessage():

[cpp]  view plain  copy
  1. BOOL AfxInternalPreTranslateMessage(MSG* pMsg)  
  2. {  
  3. //  ASSERT_VALID(this);  
  4.   
  5.     CWinThread *pThread = AfxGetThread();  
  6.     if( pThread )  
  7.     {  
  8.         // if this is a thread-message, short-circuit this function  
  9.         if (pMsg->hwnd == NULL && pThread->DispatchThreadMessageEx(pMsg))  
  10.             return TRUE;  
  11.     }  
  12.   
  13.     // walk from target to main window  
  14.     CWnd* pMainWnd = AfxGetMainWnd();  
  15.     if (CWnd::WalkPreTranslateTree(pMainWnd->GetSafeHwnd(), pMsg))// 注意这个函数  
  16.         return TRUE;  
  17.   
  18.     // in case of modeless dialogs, last chance route through main  
  19.     //   window's accelerator table  
  20.     if (pMainWnd != NULL)  
  21.     {  
  22.          CWnd* pWnd = CWnd::FromHandle(pMsg->hwnd);  
  23.          if (pWnd->GetTopLevelParent() != pMainWnd)  
  24.             return pMainWnd->PreTranslateMessage(pMsg);  
  25.     }  
  26.   
  27.     return FALSE;   // no special processing  
  28. }  

执行 CWnd::WalkPreTranslateTree(pMainWnd->GetSafeHwnd(), pMsg)
[cpp]  view plain  copy
  1. BOOL PASCAL CWnd::WalkPreTranslateTree(HWND hWndStop, MSG* pMsg)  
  2. {  
  3.     ASSERT(hWndStop == NULL || ::IsWindow(hWndStop));  
  4.     ASSERT(pMsg != NULL);  
  5.   
  6.     // walk from the target window up to the hWndStop window checking  
  7.     //  if any window wants to translate this message  
  8.   
  9.     for (HWND hWnd = pMsg->hwnd; hWnd != NULL; hWnd = ::GetParent(hWnd))  
  10.     {  
  11.         CWnd* pWnd = CWnd::FromHandlePermanent(hWnd);  
  12.         if (pWnd != NULL)  
  13.         {  
  14.             // target window is a C++ window  
  15.             if (pWnd->PreTranslateMessage(pMsg))  
  16.                 return TRUE; // trapped by target window (eg: accelerators)  
  17.         }  
  18.   
  19.         // got to hWndStop window without interest  
  20.         if (hWnd == hWndStop)  
  21.             break;  
  22.     }  
  23.     return FALSE;       // no special processing  
  24. }  
MFC在后台维护了一个句柄和C++对象指针的映射表,一旦有消息产生时,我们知道这个消息的结构体中包含了该消息所属窗口的句柄,那么通过这个句柄我们可以找到相对于的C++对象的指针,在for循环里面遍历当前窗口的所有父窗口,查找是否有消息重写,一旦有子类重写父类消息的,则通过当前消息所属窗口的句柄来调用 CWnd::FromHandlePermanent(hWnd)  函数,从而得到当前C++对象的指针,最后调用 PreTranslateMessage(),因为  PreTranslateMessage()是虚函数,所以调用的是子类的 PreTranslateMessage(),该函数可以自定义一部分消息的处理方式。

需要注意的是,PreTranslateMessage() 返回为 FALSE 时,说明没有发生消息的重写,则把消息直接给 TranslateMessage() 和DispatchMessage() 进行处理,当返回是TRUE时,则去消息队列获取下一条消息。

另外,SendMessage() 是直接发送给WindowProc进行处理(该函数是一个DispatchMessage() 中的一个回调函数,用于处理默认的一些系统消息),没有进入消息队列,所以不会被GetMessage() 抓取到,所以也就不会PreTranslateMessage() 抓到了,但是PostMessage() 是进入消息队列的,是可以被GetMessage() 抓到的。

所以从上面的代码跟踪可见,当我们需要重写一些系统消息时,比如给程序设置一些快捷键等,可以在PreTranslateMessage() 中进行操作,当然,不是PreTranslateMessage() 并不是可以重写所有消息,有一些消息也是无法处理的,这时可以交给WindowProc 进行处理,WindowProc () 也是虚函数。

[cpp]  view plain  copy
  1. LRESULT CWnd::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)  
  2. {  
  3.     // OnWndMsg does most of the work, except for DefWindowProc call  
  4.     LRESULT lResult = 0;  
  5.     if (!OnWndMsg(message, wParam, lParam, &lResult))  
  6.         lResult = DefWindowProc(message, wParam, lParam);  
  7.     return lResult;  
  8. }  
消息的映射主要是通过 OnWndMsg() 进行处理,考虑到该函数代码很多,就不全贴了,我们分析其中一小段:

[cpp]  view plain  copy
  1. for (/* pMessageMap already init'ed */; pMessageMap->pfnGetBaseMap != NULL;  
  2.     pMessageMap = (*pMessageMap->pfnGetBaseMap)())  
  3. {  
  4.     // Note: catch not so common but fatal mistake!!  
  5.     //      BEGIN_MESSAGE_MAP(CMyWnd, CMyWnd)  
  6.     ASSERT(pMessageMap != (*pMessageMap->pfnGetBaseMap)());  
  7.     if (message < 0xC000)  
  8.     {  
  9.         // constant window message  
  10.         if ((lpEntry = AfxFindMessageEntry(pMessageMap->lpEntries,  
  11.             message, 0, 0)) != NULL)  
  12.         {  
  13.             pMsgCache->lpEntry = lpEntry;  
  14.             winMsgLock.Unlock();  
  15.             goto LDispatch;  
  16.         }  
  17.     }  
  18.     else  
  19.     {  
  20.         // registered windows message  
  21.         lpEntry = pMessageMap->lpEntries;  
  22.         while ((lpEntry = AfxFindMessageEntry(lpEntry, 0xC000, 0, 0)) != NULL)  
  23.         {  
  24.             UINT* pnID = (UINT*)(lpEntry->nSig);  
  25.             ASSERT(*pnID >= 0xC000 || *pnID == 0);  
  26.                 // must be successfully registered  
  27.             if (*pnID == message)  
  28.             {  
  29.                 pMsgCache->lpEntry = lpEntry;  
  30.                 winMsgLock.Unlock();  
  31.                 goto LDispatchRegistered;  
  32.             }  
  33.             lpEntry++;      // keep looking past this one  
  34.         }  
  35.     }  
  36. }  

在for循环里面有这样一个数据: AFX_MSGMAP* pMessageMap() ,它代表当前C++对象的消息映射表指针,那么这里的消息映射表到底是个什么样的数据结构,我们来一探究竟。我们打开一个MFC工程,然后再打开一个类,比如我们打开CMainFrm 这个类,在其头文件中,我们看到有一个宏:DECLARE_MESSAGE_MAP(),进入定义看看:

[cpp]  view plain  copy
  1. #define DECLARE_MESSAGE_MAP() \  
  2. protected: \  
  3.     static const AFX_MSGMAP* PASCAL GetThisMessageMap(); \  
  4.     virtual const AFX_MSGMAP* GetMessageMap() const; \  

我们可以发现 这个宏只是声明了两个函数原型。再打开CMainFrm.cpp ,我们看到有两个宏:BEGIN_MESSAGE_MAP() 和 END_MESSAGE_MAP(),看代码:

[cpp]  view plain  copy
  1. #define BEGIN_MESSAGE_MAP(theClass, baseClass) \  
  2.     PTM_WARNING_DISABLE \  
  3.     const AFX_MSGMAP* theClass::GetMessageMap() const \  
  4.         { return GetThisMessageMap(); } \  
  5.     const AFX_MSGMAP* PASCAL theClass::GetThisMessageMap() \  
  6.     { \  
  7.         typedef theClass ThisClass;                        \  
  8.         typedef baseClass TheBaseClass;                    \  
  9.         static const AFX_MSGMAP_ENTRY _messageEntries[] =  \  
  10.         {  
  11.   
  12. #define END_MESSAGE_MAP() \  
  13.         {0, 0, 0, 0, AfxSig_end, (AFX_PMSG)0 } \  
  14.     }; \  
  15.         static const AFX_MSGMAP messageMap = \  
  16.         { &TheBaseClass::GetThisMessageMap, &_messageEntries[0] }; \  
  17.         return &messageMap; \  
  18.     }                                 \  
  19.     PTM_WARNING_RESTORE  

从代码中可见其实这两个宏定义了一个变量:AFX_MSGMAP messageMap 和两个函数 GetMessageMap() 、GetThisMessageMap()。那么 AFX_MSGMAP 是什么数据结构呢,我们继续看代码:

[cpp]  view plain  copy
  1. struct AFX_MSGMAP  
  2. {  
  3.     const AFX_MSGMAP* (PASCAL* pfnGetBaseMap)();  
  4.     const AFX_MSGMAP_ENTRY* lpEntries;  
  5. };  
又出现了一个数据结构:AFX_MSGMAP_ENTRY,不怕,我们继续看这个数据的定义:

[cpp]  view plain  copy
  1. struct AFX_MSGMAP_ENTRY  
  2. {  
  3.     UINT nMessage;   // windows message  
  4.     UINT nCode;      // control code or WM_NOTIFY code  
  5.     UINT nID;        // control ID (or 0 for windows messages)  
  6.     UINT nLastID;    // used for entries specifying a range of control id's  
  7.     UINT_PTR nSig;       // signature type (action) or pointer to message #  
  8.     AFX_PMSG pfn;    // routine to call (or special value)  
  9. };  

到此,主要的两个数据结构都已经出来了,一个是AFX_MSGMAP,另一个是AFX_MSGMAP_ENTRY ,其中后者包含在前者当中,看代码注释我们可以大致猜出来 AFX_MSGMAP_ENTRY 代表一条消息的所有信息,所以AFX_MSGMAP的作用就是两个了,一个是保存当前对象的消息映射表,另一个是获取基类的消息映射表!所以我们可以回想CMainFrm类中头文件里的 DECLARE_MESSAGE_MAP() 宏就是函数原型声明,而.cpp 文件中的两个宏之间则定义了一个数组,该数组保存当前类的消息映射表项,每一项表示某一条消息对应的处理函数等信息。

回到OnWndMsg() 中的for循环里面, 程序从当前对象开始先上遍历,获取对象的消息映射表指针,然后执行 AfxFindMessageEntry() 函数,该函数什么作用呢?我们还是看代码:

[cpp]  view plain  copy
  1. wincore.cpp  
  2.   
  3. /  
  4. // Routines for fast search of message maps  
  5.   
  6. const AFX_MSGMAP_ENTRY* AFXAPI  
  7. AfxFindMessageEntry(const AFX_MSGMAP_ENTRY* lpEntry,  
  8.     UINT nMsg, UINT nCode, UINT nID)  
  9. {  
  10. #if defined(_M_IX86) && !defined(_AFX_PORTABLE)  
  11. // 32-bit Intel 386/486 version.  
  12.   
  13.     ASSERT(offsetof(AFX_MSGMAP_ENTRY, nMessage) == 0);  
  14.     ASSERT(offsetof(AFX_MSGMAP_ENTRY, nCode) == 4);  
  15.     ASSERT(offsetof(AFX_MSGMAP_ENTRY, nID) == 8);  
  16.     ASSERT(offsetof(AFX_MSGMAP_ENTRY, nLastID) == 12);  
  17.     ASSERT(offsetof(AFX_MSGMAP_ENTRY, nSig) == 16);  
  18.   
  19.     _asm  
  20.     {  
  21.             MOV     EBX,lpEntry // 获取消息映射入口地址,即第一条消息映射地址  
  22.             MOV     EAX,nMsg// 获取当前消息  
  23.             MOV     EDX,nCode// 获取当前消息Code  
  24.             MOV     ECX,nID// 获取当前消息ID号  
  25.     __loop:  
  26.             CMP     DWORD PTR [EBX+16],0        ; nSig (0 => end)<span style="white-space:pre">      </span>  
  27.             JZ      __failed  
  28.             CMP     EAX,DWORD PTR [EBX]         ; nMessage// 判断当前消息与当前消息映射表项的消息是否相等  
  29.             JE      __found_message<span style="white-space:pre">   </span>// 相等则跳至_found_message  
  30.     __next:  
  31.             ADD     EBX,SIZE AFX_MSGMAP_ENTRY// 否则跳至下一条消息映射表项  
  32.             JMP     short __loop  
  33.     __found_message:  
  34.             CMP     EDX,DWORD PTR [EBX+4]       ; nCode// 判断code号是否相等  
  35.             JNE     __next  
  36.     // message and code good so far  
  37.     // check the ID  
  38.             CMP     ECX,DWORD PTR [EBX+8]       ; nID<span style="white-space:pre">     </span>  
  39.             JB      __next  
  40.             CMP     ECX,DWORD PTR [EBX+12]      ; nLastID  
  41.             JA      __next  
  42.     // found a match  
  43.             MOV     lpEntry,EBX                 ; return EBX// 找到对应的消息映射表项,结束  
  44.             JMP     short __end  
  45.     __failed:  
  46.             XOR     EAX,EAX                     ; return NULL  
  47.             MOV     lpEntry,EAX  
  48.     __end:  
  49.     }  
  50.     return lpEntry;  
  51. #else  // _AFX_PORTABLE  
  52.     // C version of search routine  
  53.     while (lpEntry->nSig != AfxSig_end)  
  54.     {  
  55.         if (lpEntry->nMessage == nMsg && lpEntry->nCode == nCode &&  
  56.             nID >= lpEntry->nID && nID <= lpEntry->nLastID)  
  57.         {  
  58.             return lpEntry;  
  59.         }  
  60.         lpEntry++;  
  61.     }  
  62.     return NULL;    // not found// 没有发现消息表项,返回NULL  
  63. #endif  // _AFX_PORTABLE  
  64. }  

分析上面的汇编,我们发现它把当前消息与传入的C++对象消息映射表做一一比较,当找到消息时,就返回当前AFX_MSGMAP_ENTRY 地址,进一步做处理,当找不到时,则返回NULL。所以OnWndMsg() 函数的作用就是从用户定义的消息映射表中寻找是否有重写的消息项,如果找到则返回TRUE,否则返回FALSE, 此时由 WindowProc()  来执行系统默认的消息处理函数 DefWindowProc(), 所以我们也可以在这个函数里重写一些消息响应函数。

总结

从上面的分析可以大致看出MFC的消息处理流程,即程序从GetMessage() 从消息队列中取消息,然后用 PreTranslateMessage() 函数判断是否发生用户的消息重写,如果重写了,则取下一条消息,否则将消息交给WindowProc() 处理,WIndowProc() 首先在OnWndMsg() 判断当前消息是否在当前对象的消息映射表中,如果存在,则执行用户定义的该消息对应的响应函数,否则将消息交给 DefWindowProc() 处理,我们也可以重写 DefWIndowProc() 从而实现消息的自定义处理。

4
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值