Win32下的消息流程清晰明了,但在MFC下,由于封裝的緣故,隐藏的有點深,對一般的開發人員而言,就不甚明了喽。本文試圖粗略展示出MFC下消息處理的基本流程。
一、先看一下Win32下的消息處理流程
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
二、MFC下的消息處理流程
BOOL AFXAPI AfxInternalPumpMessage()
MSG msg;
::GetMessage(&msg, NULL, NULL, NULL);
if (!AfxPreTranslateMessage(&msg))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
return TRUE;
注:以上代碼為示意代碼,具體請參照MFC的源碼。
LRESULT CALLBACK AfxWndProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam)
CWnd* pWnd = CWnd::FromHandlePermanent(hWnd); //從HWND擷取對應的CWnd*
if (pWnd == NULL || pWnd->m_hWnd != hWnd)
return ::DefWindowProc(hWnd, nMsg, wParam, lParam);
else
return pWnd->WindowProc(nMsg, wParam, lParam);
很顯然,調用了CWnd類的虛函數virtual CWnd::WindowProc處理。
LRESULT CWnd::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
// OnWndMsg does most of the work, except for DefWindowProc call
LRESULT lResult = 0;
if (!OnWndMsg(message, wParam, lParam, &lResult))
lResult = DefWindowProc(message, wParam, lParam);
return lResult;
WindowProc函數又調用了CWnd類的虛函數virtual CWnd::OnWndMsg處理。
BOOL CWnd::OnWndMsg(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult)
union MessageMapFunctions mmf;
mmf.pfn = 0;
CInternalGlobalLock winMsgLock;
// special case for commands
if (message == WM_COMMAND)
if (OnCommand(wParam, lParam))
{
lResult = 1;
goto LReturnTrue;
}
return FALSE;
// special case for notifies
if (message == WM_NOTIFY)
NMHDR* pNMHDR = (NMHDR*)lParam;
if (pNMHDR->hwndFrom != NULL && OnNotify(wParam, lParam, &lResult))
......