Change MenuItem header at runtime

I have a Menu with all kinds of menu items, as usual. Each MenuItem element (button) has a title, and I would like to change that title at runtime. On a regular button, which is actually not a problem, I just call GetDlgItem(ID)->SetWindowText(CString);

However, I cannot do this in the menu items, since I cannot assign an identifier to any of them. The ID field in the property editor actually says "ID cannot be edited."

So, how do I change the text of menu items at runtime?

EDIT . I tried using CMenu :: ModifyMenu, however I was unsuccessful. I do not know how to specify the button (element) to change. In addition, I have doubts about the correctness of how I pass CString as an argument.

This is my unsuccessful attempt:

 CString str = "Foo"; CMenu * pMenu = m_wndToolBar.GetMenu(); pMenu->ModifyMenu(1, MF_BYPOSITION | MF_STRING, 0 /*Don't know what to pass as nIDNewItem */, str); 

This (calling the ModifyMenu method) throws a debug assertion error. Please, not that I do not know what nIDNewItem is.

+8
user-interface mfc visual-studio-2003 menuitem menu
source share
4 answers

First you should get the menu command identifier. Try the following:

 tr = L"Foo"; CMenu * pMenu = m_wndToolBar.GetMenu(); MENUITEMINFO info; info.cbSize = sizeof(MENUITEMINFO); info.fMask = MIIM_ID; VERIFY(pMenu->GetMenuItemInfo(1, &info, TRUE)); pMenu->ModifyMenuW(info.wID, MF_BYCOMMAND | MF_STRING, info.wID, tr); 
+5
source share

You can try to add the ON_UPDATE_COMMAND_UI handler for the menu option and call pCmdUI->SetText() on it.

+4
source share

Menus are not windows; they are menus. You cannot use GetDlgItem to access the menu.

In MFC, the CMenu class can be used to create and / or manage menus. CMenu :: ModifyMenu may be what you are looking for.

0
source share

Are you sure the GetMenu call returns a valid CMenu? Try only GetMenu () instead of m_wndToolBar.GetMenu () .

Your ModifyMenu call seems correct, if you pass MF_BYPOSITION, you do not need the third parameter. Also note that the first parameter (position) starts at 0.

0
source share

All Articles