实现步骤:
第一步:在VC++中新建工程Message,所有ClassWizard步骤选项均为缺省,完成。
第二步:在资源中建立对话框TestDialog,通过ClassWizard添加新类TestDialog,添加“Test”按钮,
增加按钮事件OnDialogTest().
void TestDialog::OnDialogTest()
{
// TODO: Add your control notification handler code here
CMDIFrameWnd *pFrame;
CMDIChildWnd *pChild;
CView* pView;
pFrame = (CMDIFrameWnd*)AfxGetApp()->m_pMainWnd;
pChild = (CMDIChildWnd*)pFrame->GetActiveFrame();
pView = pChild->GetActiveView();
if(pView != NULL)
{
pView->PostMessage(WM_MY_MESSAGE, 0, 0);
}
}
第三步:在Message.h头文件中添加如下语句:
static UINT WM_MY_MESSAGE=RegisterWindowMessage("Message");
第四步:在视类CMessageView中添加自定义消息:
1) 在头文件MessageView.h中添加消息映射
protected:
//{{AFX_MSG(CMessageView)
//}}AFX_MSG
afx_msg LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam); //此行为添加代码
DECLARE_MESSAGE_MAP()
2)在视类文件MessageView.cpp中的消息映射中添加自定义消息映射
BEGIN_MESSAGE_MAP(CMessageView, CView)
//{{AFX_MSG_MAP(CMessageView)
//}}AFX_MSG_MAP
// Standard printing commands
ON_REGISTERED_MESSAGE(WM_MY_MESSAGE,OnMyMessage) //此行添加代码定义唯一消息
END_MESSAGE_MAP()
3) 添加相应的消息处理函数
LRESULT CMessageView::OnMyMessage(WPARAM wParam, LPARAM lParam)
{
CRect rect;
GetClientRect(&rect);
InvalidateRect(&rect);
test=!test;
return 0;
}
在MessageView.h中添加布尔变量 public:BOOL test;
在视类构造函数中初始化 test变量:test=FALSE;
4) 修改CMessageView::OnDraw()函数
void CMessageView::OnDraw(CDC* pDC)
{
CMessageDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// 以下程序显示消息响应效果
if(test)
pDC->TextOut(0,0,"消息响应!");
}
第五步:在主菜单中的菜单项中增加“Test”菜单项用来调出对话框TestDialog,在框架类中建立相应函数OnTest().
在MainFrame类中包含对话框头文件:#include "TestDialog.h";
OnTest()函数中添加代码
void CMainFrame::OnTest()
{
TestDialog dialog;
dialog.DoModal();
}