c++drop-down-menumfccmfctoolbar

How to manually show CMFCToolBarComboBoxButton sub-menu?


Standard behaviour for CMFCToolBarComboBoxButton is to have a clickable button plus a drop-down arrow for displaying a submenu. I want to show the submenu independently of where the click was made. How can I do it?

My code to create the button is, more or less, the following (it has been extracted from a larger project, so I apologize for any missing not-too-important piece of code):

// In class declaration:
CMenu m_menu;
CMFCToolBar m_toolbar;

// Where toolbar initialization takes place:
m_menu.CreateMenu();
// ... populate menu

// ID_BUTTON is the ID in the resource file for the toolbar button, 0 is the index for the button icon
CMFCToolBarMenuButton button(ID_BUTTON, m_menu.GetSafeHmenu(), 0);
m_toolbar.ReplaceButton(ID_BUTTON, button);

I've been looking around for awhile and cannot find a related answer.


Solution

  • The solution happened to be very straightforward, just call the OnClick function of the CMFCToolBarComboBoxButton button from its associated ON_COMMAND.

    // ... message map
    ON_COMMAND(ID_BUTTON, OnToolbarMenuButtonClicked)
    // ...
    
    void MyWnd::OnToolbarMenuButtonClicked()
    {
      const int index = m_toolbar.CommandToIndex(ID_BUTTON);
      auto button = (CMFCToolBarComboBoxButton*)m_toolbar.GetButton(index);
      button->OnClick(NULL, TRUE);
    }
    

    This behaviour is not documented and, contrary to what common sense told me, it doesn't create an infinite recursive call. It seems that the "main" button is still controlled by CMFCToolBarButton, while just the "arrow-button" is controlled by the CMFCToolBarComboBoxButton.

    PS: obviously, and out of the scope of the question, the OnToolbarMenuButtonClicked can be used for a very different purpose, such as the default action while the sub-menu contains other less-frequent options.