Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 372
David Božjak Avatar asked Jun 17 '11 09:06

David Božjak


3 Answers

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);
like image 174
fred.yu Avatar answered Nov 02 '22 12:11

fred.yu


You could try adding an ON_UPDATE_COMMAND_UI handler for the menu option, and calling pCmdUI->SetText() in it.

like image 6
john_e Avatar answered Nov 02 '22 14:11

john_e


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.

like image 1
Ajay Avatar answered Nov 02 '22 12:11

Ajay