假设我有一个名为 CListCtrlStyled 的网格类,它派生自 CWnd(MFC 的内置类)。
假设我有另一个名为 Parent 的类,它使用 CListCtrlStyled 的实例,并映射到列表控件。例如。
void Parent::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST_CONTROL, listCtrl);
}
CListCtrlStyled 也有自己的函数和处理程序。它将以这种方式处理右键单击事件。
BEGIN_MESSAGE_MAP(CListCtrlStyled, CListCtrl)
//{{AFX_MSG_MAP(CListCtrlStyled)
ON_NOTIFY_REFLECT_EX(NM_RCLICK, OnRclick)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
OnRclick 调用某个函数的位置取决于单击的上下文菜单选项(复制、粘贴等)。
我想在父类中处理右键单击事件,而不调用实例类中的处理程序,但我不知道如何操作。
我尝试过这样处理。
BEGIN_MESSAGE_MAP(Parent, CDialog)
//{{AFX_MSG_MAP(CListCtrlStyled)
ON_NOTIFY(NM_RCLICK, IDC_LIST_CONTROL, &Parent::OnRclick)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
虽然它确实在 Parent 类中处理右键单击,但它也在 CListCtrlStyled 类中再次处理它。
请注意,CListCtrlStyled 也在其他类中使用,因此仅编辑此类中的复制函数来适应我想要对父类执行的操作是不可行的。
最终,当我从右键单击上下文菜单中单击“复制”时,我想使用父类的复制功能而不是实例的类。
也许这个设计有缺陷?如果有另一种设计可以让我按照我所说的去做,我应该考虑,请告诉我,谢谢。
最佳答案
您(或其他人)已设计了 CListCtrlStyled
控件,它首先使用 ON_NOTIFY_REFLECT_EX(NM_RCLICK, OnRclick)
宏处理右键单击事件。该宏将 CListCtrlStyled::OnRclick
方法定义为右键单击事件的第一个处理程序。在处理程序中,您可以返回 TRUE 或 FALSE 以允许父级处理右键单击事件。但是,正如您正确注意到的那样,该事件将首先由 CListCtrlStyled
处理,然后传递给 Parent
类的处理程序。
有一种方法可以先在Parent
中处理该事件,甚至可以阻止它在CListCtrlStyled
中进行处理。您可以在 PreTranslateMessage 中执行此操作。您在发送消息之前对其进行处理,如果您返回 TRUE,CListCtrlStyled
甚至不会知道它。这是一个小代码:
BOOL Parent::PreTranslateMessage(MSG* pMsg)
{
if(pMsg->message == WM_RBUTTONUP && pMsg->hwnd == listCtrl.GetSafeHwnd())
{
// do something
// if you want to block the message from later processing then return TRUE.
// if you want to allow the handlers for NM_RCLICK to also handle the message
// then comment the line below
return TRUE;
}
return __super::PreTranslateMessage(pMsg);
}
关于c++ - MFC:调用来自不同类的函数以进行上下文菜单单击,而不是让它调用其默认函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23747418/