Search code examples
c++menumfccmfcmenubutton

CMFCMenuButton with a programmatically constructed menu?


I'm new to the CMFCMenuButton control; here's my code in OnInitDialog():

// Load application list into menu button
m_ApplicationMenu = CreateMenu();   
m_MenuInfoSize = 2;
m_MenuInfo = new MENUITEMINFO[m_MenuInfoSize];
memset(m_MenuInfo, 0, sizeof(MENUITEMINFO) * m_MenuInfoSize);
UINT menuIndex = 0;
BOOL b; 
// 1st menu item
memset(m_MenuInfo + menuIndex, 0, sizeof(MENUITEMINFO));
m_MenuInfo[menuIndex].cbSize = sizeof(MENUITEMINFO);
m_MenuInfo[menuIndex].fMask = MIIM_ID | MIIM_STRING | MIIM_DATA;
m_MenuInfo[menuIndex].wID = menuIndex;
m_MenuInfo[menuIndex].dwTypeData = new WCHAR[10]; 
swprintf_s(m_MenuInfo[menuIndex].dwTypeData, 10, L"%s", L"A1");
m_MenuInfo[menuIndex].cch = wcslen(m_MenuInfo[menuIndex].dwTypeData) + 1;
b = InsertMenuItem(m_ApplicationMenu, menuIndex, TRUE, &(m_MenuInfo[menuIndex]));
menuIndex++;
// 2nd menu item
memset(&m_MenuInfo[menuIndex], 0, sizeof(MENUITEMINFO));
m_MenuInfo[menuIndex].cbSize = sizeof(MENUITEMINFO);
m_MenuInfo[menuIndex].fMask = MIIM_ID | MIIM_STRING | MIIM_DATA;
m_MenuInfo[menuIndex].wID = menuIndex;
m_MenuInfo[menuIndex].dwTypeData = new WCHAR[10]; 
swprintf_s(m_MenuInfo[menuIndex].dwTypeData, 10, L"%s", L"B2");
m_MenuInfo[menuIndex].cch = wcslen(m_MenuInfo[menuIndex].dwTypeData) + 1;
b = InsertMenuItem(m_ApplicationMenu, menuIndex, TRUE,  &(m_MenuInfo[menuIndex]));
menuIndex++;
// Attach menu to CMFCMenuButton
m_ApplicationList.m_bOSMenu = TRUE;
m_ApplicationList.m_bRightArrow = FALSE;
m_ApplicationList.m_bStayPressed = TRUE;
m_ApplicationList.m_bDefaultClick = FALSE;
m_ApplicationList.m_hMenu = m_ApplicationMenu;
    // Testing the constructed menu with the dialog's menu bar
::SetMenu(this->m_hWnd, m_ApplicationMenu);

When I ran the application, the CMFCMenuButton displayed a dropdown menu when I clicked on it... but those two items were empty, no text and no image.

I added the last line to test my constructed menu; and the two items showed up in the menu bar properly.

I also tried using a menu created from the resource editor. It showed up fine in menu bar, but in the CMFCMenuButton, there were again empty spaces.

What did I miss?


Solution

  • Try

    m_ApplicationMenu = CreatePopupMenu();
    

    Also, you'd better use 1 as the first menuIndex if you want to get the m_nMenuResult of CMFCMenuButton in click event. Because:

    CMFCMenuButton::m_nMenuResult

    An integer that indicates which item the user selects from the pop-up menu.

    The value of this member variable is zero if the user cancels the menu without making a selection or if an error occurs.