在运行时更改菜单项标题
我有一个包含各种菜单项的菜单,就像您通常所做的那样。每个菜单项(按钮)都有一个标题,我想在运行时更改该标题。在并不是真正问题的普通按钮上,我只需调用 GetDlgItem(ID)->SetWindowText(CString);
但是,我无法在菜单项上执行此操作,因为我不能为其中任何一个分配 ID。属性编辑器中的 ID 字段实际上显示“ID 无法编辑”。
那么如何在运行时更改菜单项文本呢?
编辑:我尝试使用 CMenu::ModifyMenu 但没有成功。我不知道如何指定要更改的按钮(元素)。另外,我对将 CString 作为参数传递的方式的正确性存有疑问。
这是我的(失败的)尝试:
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);
这(对ModifyMenu 方法的调用)引发了调试断言错误。请注意,我不知道 nIDNewItem 是什么。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以尝试为菜单选项添加
ON_UPDATE_COMMAND_UI
处理程序,并在其中调用pCmdUI->SetText()
。You could try adding an
ON_UPDATE_COMMAND_UI
handler for the menu option, and callingpCmdUI->SetText()
in it.您应该首先获取菜单项的命令 ID。试试这个:
You should get menu item's command id first. Try this:
菜单不是窗口,它们只是菜单。您不能使用
GetDlgItem
访问菜单。在 MFC 中,
CMenu
类可用于创建和/或控制菜单。CMenu::ModifyMenu
可能就是您正在寻找的东西。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.您确定对
GetMenu
的调用返回有效的 CMenu 吗?尝试仅调用GetMenu()
而不是m_wndToolBar.GetMenu()
。您对 ModifyMenu 的调用似乎是正确的,如果您传递 MF_BYPOSITION ,则不需要第三个参数。另请注意,第一个参数(位置)从 0 开始。
Are you sure that the call to
GetMenu
is returning a valid CMenu? Try calling onlyGetMenu()
instead ofm_wndToolBar.GetMenu()
.Your call to
ModifyMenu
seems to be right, if you pass aMF_BYPOSITION
you do not need the 3rd parameter. Also note that the 1st parameter (position) starts at 0.