CMFCMenuButton does not close

2019-06-01 17:15发布

问题:

I have a CDialog with a CFMCMenuButton. when I open it, everything appears normally:

The problem happens when I click somewhere else to close the menu. The menu seems unclosable, unless user selects an option of it. And if I press Escape on the keyboard, the dialog closes itself, which is too drastic; I really would want it to close only the menu.

I know I could solve this by setting its property "OS Menu" in the resource file to True (or equivalently, assigning its property m_bOSMenu= TRUE). And I would get:

As you can see in the image, the consequences are :

  • I loose the icons (not very important)
  • I loose some items' disablings (important) done by OnInitMenuPopup (side note: the second menucolumn is also done by OnInitMenuPopup and it appears as it should be). If user clicks in these options, they will work and they SHOULD NOT.

How can I solve the problem?

回答1:

The answer comes from straight from the MFC source.

The file afxmenubutton.cpp in its CMFCMenuButton::OnShowMenu function advises to use a CDialogEx instead of a CDialog:

#ifdef _DEBUG
    if ((pParent->IsKindOf(RUNTIME_CLASS(CDialog))) && (!pParent->IsKindOf(RUNTIME_CLASS(CDialogEx))))
    {
        TRACE(_T("CMFCMenuButton parent is CDialog, should be CDialogEx for popup menu handling to work correctly.\n"));
    }
#endif

Then I changed my dialog class to derive from CDialogEx, and now everything works perfectly! Having the OS Menu property as False, icons are shown and the disabled options are really disabled and grayed out!

UPDATE: Some documentation on https://msdn.microsoft.com/en-us/library/Bb983913.aspx