Change MenuItem caption at runtime
Asked Answered
H

4

9

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.

Hagiolatry answered 17/6, 2011 at 9:3 Comment(0)
K
7

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

Khudari answered 15/7, 2011 at 20:10 Comment(0)
M
7

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);
Monopolize answered 22/2, 2013 at 6:53 Comment(0)
G
1

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.

Gem answered 21/6, 2011 at 15:23 Comment(1)
Thank you for your answer. I have stumbled upon CMenu::ModifyMenu before, however I didn't succeed in changing the caption. Please see my edited question! Thanks!Kory
P
1

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.

Pinnatiped answered 26/7, 2011 at 17:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.