由于 MFC 不允许捕获 CButton 控件上的所有事件,但有一些常用的事件,如 BN_CLICKED 和 BN_DOUBLECLICKED。因此,要在 CButton MFC 上捕获鼠标右键事件,您需要从 CButton 派生一个新类。
MyButton.h
#if !defined(AFX_MYBUTTON_H__46A1ECCC_0FAD_485A_B6B8_C21B6538148E__INCLUDED_)
#define AFX_MYBUTTON_H__46A1ECCC_0FAD_485A_B6B8_C21B6538148E__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// MyButton.h : header file
// CMyButton window
class CMyButton : public CButton //CMyButton =>derive from the CButton.
{
// Construction
public:
CMyButton();
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMyButton)
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CMyButton();
// Generated message map functions
protected:
//{{AFX_MSG(CMyButton)
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#endif // !defined(AFX_MYBUTTON_H__46A1ECCC_0FAD_485A_B6B8_C21B6538148E__INCLUDED_)
MyButton.cpp
#include "stdafx.h"
#include "MyButton.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMyButton
CMyButton::CMyButton()
{
}
CMyButton::~CMyButton()
{
}
BEGIN_MESSAGE_MAP(CMyButton, CButton)
//{{AFX_MSG_MAP(CMyButton)
ON_WM_RBUTTONUP()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMyButton message handlers
void CMyButton::OnRButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
NMHDR hdr;
hdr.code = NM_RCLICK;
hdr.hwndFrom = this->GetSafeHwnd();
hdr.idFrom = GetDlgCtrlID();
TRACE("OnRButtonUp");
this->GetParent()->SendMessage(WM_NOTIFY, (WPARAM)hdr.idFrom, (LPARAM)&hdr);
}
现在在您的 Dialog 类中,您需要捕获您的 CMyButton 传递的消息。传递的消息是 NM_RCLICK,您将其捕获为
ON_NOTIFY(NM_RCLICK, IDC_BUTTON1, OnRClicked)
您的成员函数必须使用以下原型声明:
afx_msg void OnRClicked( NMHDR * pNotifyStruct, LRESULT * result );
更多详情可以点击链接mouse-button-event-handler