当MFC所提供的控件不能满足我们的要求时,我们需要为控件进行功能扩展,根据需求自定义控件的事件。本文以一个扩展按钮的鼠标按下和鼠标松开的事件为例,其它控件事件扩展可遵照该例。提供源代码,在VC6.0中调试成功。
按钮也是一个窗口,继承自CWND,它其中封装了大量的消息,因此我们之需要继承CButton,然后添加我们需要的事件对控件进行扩展即可。在开发过程中,只需要将标准按钮拖放到对话框,这和一般开发没有区别。
基本思想:一般不需要将在新扩展类中编写消息相应代码,而是将该消息反射到父窗口中去,原因是因为在处理消息的过程中,我们需要用到父窗口的其他信息,如果放在这个类中去实现,很麻烦,也基本不可能。
开发流程:
一 新建一个类NewButton,继承CButton,需要做如下工作:
- 添加事件OnLButtonDown OnLButtonUp 。
- 添加HWND成员变量 HWND m_hWnd.
- 添加消息宏道头文件中 #define WM_LBUTTONDOWNU (WM_USER+10)
#define WM_LBUTTONUPU (WM_USER+11) - 添加自定义消息 //{{AFX_MSG(NewButton)
// NOTE - the ClassWizard will add and remove member functions here.
afx_msg void OnLButtonDown(UINT nFlags,CPoint point);
afx_msg void OnLButtonUp(UINT nFlags,CPoint point);
//}}AFX_MSG - 实现2个事件函数
void NewButton::OnLButtonDown(UINT nFlags,CPoint point)
{
CButton::OnLButtonDown(nFlags,point);
UINT id =GetDlgCtrlID();
m_hWnd = GetParent()->GetSafeHwnd();
::SendMessage(m_hWnd,WM_LBUTTONDOWNU,id,0);
}
void NewButton::OnLButtonUp(UINT nFlags,CPoint point)
{
CButton::OnLButtonUp(nFlags,point);
UINT id;
id=GetDlgCtrlID();
m_hWnd=GetParent()->GetSafeHwnd();
::SendMessage(m_hWnd,WM_LBUTTONUPU,id,0);
}
二 在对话框中放置2个按钮 界面如下:
- 添加2个事件 afx_msg void OnLButtonDownu(UINT id,UINT qt);
afx_msg void OnLButtonUpu(UINT id,UINT qt); - 添加消息映射 BEGIN_MESSAGE_MAP(CButtonExtDlg, CDialog)
//{{AFX_MSG_MAP(CButtonExtDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_CANCELMODE()
//}}AFX_MSG_MAP
ON_MESSAGE(WM_LBUTTONDOWNU, OnLButtonDownu)
ON_MESSAGE(WM_LBUTTONUPU, OnLButtonUpu)
END_MESSAGE_MAP() - 在OnIniDilog中添加代码 m_button1.SubclassDlgItem(IDC_BUTTON1,this);
m_button2.SubclassDlgItem(IDC_BUTTON2,this); - 实现2个消息响应函数,对消息进行处理。
- void CButtonExtDlg::OnLButtonDownu(UINT id,UINT qt)
{
if(id==IDC_BUTTON1)
{
GetDlgItem(IDC_EDIT_TEST)->SetWindowText("BUTTON1 DOWN");
}
if(id==IDC_BUTTON2)
{
GetDlgItem(IDC_EDIT_TEST)->SetWindowText("BUTTON2 DOWN");
}
} - void CButtonExtDlg::OnLButtonUpu(UINT id,UINT qt)
{
if(id==IDC_BUTTON1)
{
GetDlgItem(IDC_EDIT_TEST)->SetWindowText("BUTTON1 UP");
}
if(id==IDC_BUTTON2)
{
GetDlgItem(IDC_EDIT_TEST)->SetWindowText("BUTTON2 UP");
}
}