Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get Submenu in MFC?

I'm trying to get a submenu so that I can make changes to it before it is displayed.

So I created an OnInitMenu() handler for my window. And I had planned to use pMenu->GetMenuItemInfo() to get the submenu.

However, it doesn't appear this will work. In order to locate the menu I want, I must supply the menu command ID (I do not consider it satisfactory to hard code item positions). But menu items that open submenus do not have command IDs. I can get a menu command that exists inside that submenu, but then I still don't have the menu itself.

How can I locate a submenu nested in my main menu, without relying on MF_BYPOSITION?

like image 501
Jonathan Wood Avatar asked Apr 28 '12 16:04

Jonathan Wood


2 Answers

My solution to this same problem was to create a helper function to search through the menu and return the position based on the name of the menu.

int CEnviroView::FindMenuItem(CMenu* Menu, LPCTSTR MenuName) {
    int count = Menu->GetMenuItemCount();
    for (int i = 0; i < count; i++) {
        CString str;
        if (Menu->GetMenuString(i, str, MF_BYPOSITION) &&
            str.Compare(MenuName) == 0)
            return i;
    }
    return -1;
}
like image 139
joakaune Avatar answered Sep 27 '22 23:09

joakaune


It appears the answer is that you can't. Using command IDs to locate a menu command makes great sense because such code will continue to work as you rearrange menu items. However, menu items that are sub menus simply do not have a command ID.

One approach is to have a known menu command, which you can search for by ID, and then insert new items next to that command. However, you still need the containing menu.

The approach I ended up using resulted from studying the code MFC uses to populate the most recently used file list in the File menu. The general technique is described in the somewhat dated Paul DiLascia's Q & A column from Microsoft Systems Journal.

like image 40
Jonathan Wood Avatar answered Sep 28 '22 00:09

Jonathan Wood