1.在MESSAGE_MAP中添加响应函数:
MESSAGE_MAP表中定义了消息响应函数,其格式为:消息名(ID,函数名),当我们用ClassWizard添加函数时,会自动添加在AFX_MSG_MAP括起的区间内,如:
| BEGIN_MESSAGE_MAP(CTextEditorView, CFormView) //{{AFX_MSG_MAP(CTextEditorView) ON_BN_CLICKED(IDC_ICONBUT0, OnIconbut0) //}}AFX_MSG_MAP END_MESSAGE_MAP() |
手工添加时不要添加到AFX_MSG_MAP区间内,以防ClassWizard不能正常工作,如:
| BEGIN_MESSAGE_MAP(CTextEditorView, CFormView) //{{AFX_MSG_MAP(CTextEditorView) ON_BN_CLICKED(IDC_ICONBUT0, OnIconbut0) //}}AFX_MSG_MAP ON_BN_CLICKED(ID_MYBUT1, OnMybut1) ON_BN_CLICKED(ID_MYBUT2, OnMybut2) ON_BN_CLICKED(ID_MYBUT3, OnMybut3) END_MESSAGE_MAP() |
其中ON_BN_CLICKED是按钮单击消息。
2.在头文件中添加函数定义:
用ClassWizard添加函数时,会在头文件的AFX_MSG区间内添加函数定义,如:
| protected: //{{AFX_MSG(CTextEditorView) afx_msg void OnIconbut0(); //}}AFX_MSG DECLARE_MESSAGE_MAP() |
我们模仿这种形式,只是把函数定义添加到AFX_MSG区间外就行了:
| protected: //{{AFX_MSG(CTextEditorView) afx_msg void OnIconbut0(); //}}AFX_MSG afx_msg void OnMybut1(); afx_msg void OnMybut2(); afx_msg void OnMybut3(); DECLARE_MESSAGE_MAP() |
3.编写消息响应函数:
以上是把消息和函数关联起来了,具体在单击按钮后应做的工作在函数中完成:
| void CTextEditorView::OnMybut1() { MessageBox( "哈!你单击了动态按钮。" ); } void CTextEditorView::OnMybut2() { …… } void CTextEditorView::OnMybut3() { …… } |
除了按钮的响应函数外,你还可以用上面获得的指针访问按钮,如:
修改按钮的大小和位置:p_MyBut[0]->MoveWindow(……);
修改按钮文本:p_MyBut[0]->SetWindowText(……);
显示/隐藏按钮:p_MyBut[0]->ShowWindow(……);等等。

