,组织两个数组_messageEntries[ ]和_commandEntries[ ],把程序中欲处理的消息以及消息处理例程的关联性建立起来:
// 消息与处理例程之对照表
struct MSGMAP_ENTRY _messageEntries[] =
{
WM_CREATE, OnCreate,
WM_PAINT, OnPaint,
WM_SIZE, OnSize,
WM_COMMAND, OnCommand,
WM_SETFOCUS, OnSetFocus,
WM_CLOSE, OnClose,
WM_DESTROY, OnDestroy,
};这是消息 这是消息处理例程
// Command-ID 与处理例程之对照表格
struct MSGMAP_ENTRY _commandEntries =
{
IDM_ABOUT, OnAbout,
IDM_FILEOPEN, OnFileOpen,
IDM_SAVEAS, OnSaveAs,
};这是WM_COMMAND命令项 这是命令处理例程
于是窗口函数可以这么设计:
// 窗口函数
LRESULT CALLBACK WndProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
int i;
for(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));
}
// OnCommand——专门处理WM_COMMAND
LONG OnCommand(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int i;
for(i=0; i < dim(_commandEntries); i++) { // 命令项目对照表
if (LOWORD(wParam) == _commandEntries[i].nMessage)
return((*_commandEntries[i].pfn)(hWnd, message, wParam, lParam));
}
return(DefWindowProc(hWnd, message, wParam, lParam));
}
//----------------------------------------------------------------------
LONG OnCreate(HWND hWnd, UINT wMsg, UINT wParam, LONG lParam)
{
...
}
//----------------------------------------------------------------------
LONG OnAbout(HWND hWnd, UINT wMsg, UINT wParam, LONG lParam)
{
`...
}
这么一来,WndProc和OnCommand永远不必改变,每有新要处理的消息,只要在_messageEntries[ ] 和 _commandEntries[ ] 两个数组中加上新元素,并针对新消息撰写新的处理例程即可。