代码比较短小,实现了消息映射。
Dialog.h :
#include <windows.h> class CDialog { public: //一条消息所包含的信息 struct MAP { UINT Msg; bool (*pf)(HWND hwndDlg,UINT uMsg,WPARAM wParam,LPARAM lParam); int len; MAP *pNext; }; public: WORD m_wRes;//Dialog资源的ID //头、尾指针,用来操作消息列表 static MAP *m_pHead; MAP *m_pEnd; public: bool Show(HINSTANCE,HWND); void AddMsg(bool (*fp)(HWND hwndDlg,UINT uMsg,WPARAM wParam,LPARAM lParam),UINT); static bool OnClose(HWND hwndDlg,UINT uMsg,WPARAM wParam,LPARAM lParam); static bool OnInit(HWND hwndDlg,UINT uMsg,WPARAM wParam,LPARAM lParam); CDialog(); private: static INT_PTR CALLBACK DialogProc(HWND hwndDlg,UINT uMsg,WPARAM wParam,LPARAM lParam); void InitMap(); }; int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow);
Dialog.cpp :
#include "Dialog.h" CDialog* pThis;//保存基类指针 CDialog::MAP* CDialog::m_pHead = NULL; //窗口过程函数 INT_PTR CDialog::DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { //遍历消息列表以查找是否有相应的响应函数 CDialog::MAP* pTemp = m_pHead; for(int i = 1;i <= m_pHead->len;++i) { if(uMsg == pTemp->Msg) { pTemp->pf(hwndDlg,uMsg,wParam,lParam); return FALSE; } pTemp = pTemp->pNext; } return FALSE; } //创建消息列表 void CDialog::InitMap() { m_pHead = new MAP; m_pHead->len = 2; m_pHead->Msg = WM_CLOSE; m_pHead->pf = OnClose; MAP *pNew = new MAP; pNew->Msg = WM_INITDIALOG; pNew->pf = OnInit; pNew->pNext = NULL; m_pHead->pNext = pNew; m_pEnd = pNew; } //消息响应函数 bool CDialog::OnClose(HWND hwndDlg,UINT uMsg,WPARAM wParam,LPARAM lParam) { EndDialog(hwndDlg,0); return true; } CDialog::CDialog() { InitMap(); } //程序入口函数 int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) { pThis->Show(hInstance,NULL); return 0; } //显示Dialog bool CDialog::Show(HINSTANCE hIns,HWND hParent) { DialogBox(hIns,MAKEINTRESOURCE(m_wRes),hParent,DialogProc); return true; } //由子类重写此函数以在对话框初始化时进行一些操作 bool CDialog::OnInit(HWND hwndDlg,UINT uMsg,WPARAM wParam,LPARAM lParam) { return true; } //向消息列表中增加消息 void CDialog::AddMsg(bool (*fp)(HWND hwndDlg,UINT uMsg,WPARAM wParam,LPARAM lParam),UINT uMsg) { MAP *pNew = new MAP; pNew->Msg = uMsg; pNew->pf = fp; pNew->pNext = NULL; m_pEnd->pNext = pNew; m_pEnd = pNew; ++m_pHead->len; }
使用时,只需要把这2个文件包含进去,用资源编辑器创建一个Dialog,然后再自己写一个类,继承我的CDialog类,把m_wRes这个成员变更设为你创建的Dialog的ID,再extern一个全局变量m_pThis并把this指针赋给它就可以了。
要增加消息响应函数的话,只要在你的类的构造函数里调用AddMsg()这个函数,然后再写你的消息响应函数就好了。
AddMsg有两个参数,第一个参数是你的消息响应函数名,第二个参数是你要响应的消息。
示例:
#include "MyDlg.h" #include "resource.h"
//定义一个指向CDialog的指针并在下面的构造函数中赋值为this extern CDialog* pThis; MyDlg App; MyDlg::MyDlg() { m_wRes = IDD_DIALOG1; pThis = this; AddMsg(OnCommand,WM_COMMAND); } //WM_COMMAND消息响应函数 bool MyDlg::OnCommand(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { MessageBox(hwndDlg,"","",0); return true; } //WM_INITDIALOG消息响应函数 bool MyDlg::OnInit(HWND hwndDlg,UINT uMsg,WPARAM wParam,LPARAM lParam) { MessageBox(hwndDlg,"","",0); return true; }