1. 定义消息映射结构
struct MSGMAP_ENTRY{
UINT nMessage;
LONG (*pfn)(HWND,UINT,WPARAM,LPARAM);
};
#define dim(x) (sizeof(x)/sizeof(x[0]))
2. 定义消息映射数组
//消息映射
struct MSGMAP_ENTRY _messageEntries[]=
{
WM_PAINT,OnPaint,
WM_LBUTTONDOWN, OnLButtonDown,
WM_DESTROY, OnDestory,
WM_COMMAND, OnCommand,
WM_KEYDOWN, OnKeyDown,
};
3. 定义COMMDND消息映射数组
struct MSGMAP_ENTRY _commandEntries[]=
{
IDM_ABOUT,OnAbout,
IDM_EXIT, OnExit,
};
4. 新的消息处理函数
LRESULT CALLBACK WndProc(
HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
int i=0;
for(int i=0;i<dim(_messageEntries);i++)
{
if(message==_messageEntries[i].nMessage)
{
return ((*_messageEntries[i].pfn)(hWnd, message, wParam, lParam));
}
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
5. OnCommand函数
LONG OnCommand(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// 分析菜单选择:
int i=0;
for(int i=0;i<dim(_commandEntries);i++)
{
if(wmId==_commandEntries[i].nMessage)
{
return ((*_commandEntries[i].pfn)(hWnd, message, wParam, lParam));
}
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
来自深入浅出MFC第一章