I must disable submenu mfc c++

Viewed 230

I must disable an item of submenu, I tried:

CMenu* pMenu = AfxGetMainWnd()->GetMenu();
CMenu* pSubMenu = pMenu->GetSubMenu(1);
if (pMenu != NULL)
{
    //for (UINT i = 0; i < pMenu->GetMenuItemCount(); ++i)
        pSubMenu->EnableMenuItem(ID_FILE_CONFRONTO_GRAFICI, MF_BYPOSITION | MF_GRAYED);
        
}
1 Answers

I solved this issue:

CMenu* pMenu = AfxGetMainWnd()->GetMenu();
CMenu * subMenu = pMenu->GetSubMenu(0);
if (subMenu != NULL)
{
        subMenu->EnableMenuItem(1, MF_BYPOSITION | MF_DISABLED);

}

Clarification

EnableMenuItem has the following definition:

UINT EnableMenuItem(
    UINT nIDEnableItem,
    UINT nEnable);`

The important thing to understand is the correct use of the last nEnable parameter. To quote:

nEnable Specifies the action to take. It can be a combination of MF_DISABLED, MF_ENABLED, or MF_GRAYED, with MF_BYCOMMAND or MF_BYPOSITION. These values can be combined by using the bitwise OR operator. These values have the following meanings:

MF_BYCOMMAND Specifies that the parameter gives the command ID of the existing menu item. This is the default.

MF_BYPOSITION Specifies that the parameter gives the position of the existing menu item. The first item is at position 0.

In the original code you had:

pSubMenu->EnableMenuItem(ID_FILE_CONFRONTO_GRAFICI, MF_BYPOSITION | MF_GRAYED);

The issue:

  1. You used MF_BYPOSITION (which means nIDEnableItem is a zero based index) yet ...
  2. You used ID_FILE_CONFRONTO_GRAFICI for the first parameter.

So there are two way to do this (with some exceptions):

  • subMenu->EnableMenuItem(1, MF_BYPOSITION | MF_DISABLED);
  • subMenu->EnableMenuItem(ID_FILE_CONFRONTO_GRAFICI, MF_BYCOMMAND | MF_DISABLED);
Related