Change MenuItem caption at runtime
I have a Menu with all sorts of Menu items, as you normally would. Every MenuItem (button) has a caption and I'd like to change that caption at runtime. On a normal button that isn't really a problem, I just call GetDlgItem(ID)->SetWindowText(CString);
However I can't do that on the menu items since I can't assign ID's to any of them. The ID field in the Properties editor actually says "ID can not be edited".
So how do I change the menu items text at runtime?
EDIT: I have tried using the CMenu::ModifyMenu however I have been unsuccessful. I 开发者_Python百科don't know how to specify the button (element) to change. Also, I have doubts in the correctness of the way I pass the CString as an argument.
This is my (failed) 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 (the call to the ModifyMenu method) throws a debug assertion error. Please not that I don't know what nIDNewItem.
You could try adding an ON_UPDATE_COMMAND_UI
handler for the menu option, and calling pCmdUI->SetText()
in it.
You should get menu item's command id first. Try this:
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);
Menus are not windows, they are menus. You cannot use GetDlgItem
to access a menu.
In MFC, CMenu
class can be used to create and/or control menus. CMenu::ModifyMenu
might be the thing you are looking for.
Are you sure that the call to GetMenu
is returning a valid CMenu? Try calling only GetMenu()
instead of m_wndToolBar.GetMenu()
.
Your call to ModifyMenu
seems to be right, if you pass a MF_BYPOSITION
you do not need the 3rd parameter. Also note that the 1st parameter (position) starts at 0.
精彩评论