| 打造自定义的 AfxMessageBox 下载源代码 int AFXAPI AfxMessageBox(LPCTSTR lpszText, UINT nType, UINT nIDHelp) { CWinApp* pApp = AfxGetApp(); if (pApp != NULL) return pApp->DoMessageBox(lpszText, nType, nIDHelp); else return pApp->CWinApp::DoMessageBox(lpszText, nType, nIDHelp); } 重载 DoMessageBox 后我们得到了什么呢? int COwnAfxMessageBoxApp::DoMessageBox(LPCTSTR lpszPrompt, UINT nType, UINT nIDPrompt) { return CWinApp::DoMessageBox(lpszPrompt, nType, nIDPrompt); } 其中 CWinApp::DoMessageBox 就是对 Windows API 中的 ::MessageBox 的封装,再此不多叙。从代码中看出,调用 AfxMessageBox 先要到 DoMessageBox 这里审核,审核通过再执行标准的MessageBox,这下你该知道怎么做了吧?到这时,可能你会这样写到: int COwnAfxMessageBoxApp::DoMessageBox(LPCTSTR lpszPrompt, UINT nType, UINT nIDPrompt) { OwnMessageBox(lpszPrompt, nType, nIDPrompt); // return CWinApp::DoMessageBox(lpszPrompt, nType, nIDPrompt); } 这样的写法没有问题,但也许有的时候仍然需要弹出标准的 MessageBox 需要用户确认,怎么设计才更加合理呢?AfxMessageBox 的第二个参数 nType 是指定 MessageBox 的类型,在 Winuser.h 中定义了一些标准的类型,请注意 nType 是 UINT 类型的,而标准类型的定义才不到10个,你完全可以添加自己的 MessageBox 类型!在 OwnAfxMessageBoxApp.h 中定义:#define MB_USERDEFINE0x10000000你的 DoMessageBox 处理函数: int COwnAfxMessageBoxApp::DoMessageBox(LPCTSTR lpszPrompt, UINT nType, UINT nIDPrompt) {if (MB_USERDEFINE == nType){OwnMessageBox(lpszPrompt, nType, nIDPrompt);return TRUE;}return CWinApp::DoMessageBox(lpszPrompt, nType, nIDPrompt);} 你的调用代码:void COwnAfxMessageBoxDlg::OnOK() {::AfxMessageBox("我是标准的 AfxMessageBox!");::AfxMessageBox("我是被重载的 AfxMessageBox!", MB_USERDEFINE);//CDialog::OnOK();} 到这里原理部分已经讲完了,具体的实现方法请查看代码。感谢 CSDN 的 bongny (金辉)提供了思路。 三、结束语 其实这个根本都称不上技术,只要善于发现就会有新的收获。祝大家身体健康,万事如意! 最后打一句广告:请关注恒金软件 - http://www.kingesoft.com ! |