Reputation: 67195
I'm trying to get a submenu so that I can make changes to it before it is displayed.
So I created an OnInitMenu()
handler for my window. And I had planned to use pMenu->GetMenuItemInfo()
to get the submenu.
However, it doesn't appear this will work. In order to locate the menu I want, I must supply the menu command ID (I do not consider it satisfactory to hard code item positions). But menu items that open submenus do not have command IDs. I can get a menu command that exists inside that submenu, but then I still don't have the menu itself.
How can I locate a submenu nested in my main menu, without relying on MF_BYPOSITION
?
Upvotes: 5
Views: 4740
Reputation: 4296
You can use the method GetSubMenu
from the class CMenu
.
http://msdn.microsoft.com/en-us/library/dtfc356x(v=vs.80).aspx
Upvotes: 1
Reputation: 1609
It would be much simpler to use MFC Command routing that allows you to update menu items? If this is MDI/SDI application you have it for free if not you will have to implement update mechanism.
Do not handle WM_INITMENU
. You should handle WM_INITMENUPOPUP
. WM_INITMENUPOPUP
delivers pointer to the menu that is just about to popup.
In the handler you can write a code that will allow dialog updating specific menu items using UI update mechanism fo all menus, or you can handle only a change to the specific menu item you have to alter in the handler.
Upvotes: 2
Reputation: 141
My solution to this same problem was to create a helper function to search through the menu and return the position based on the name of the menu.
int CEnviroView::FindMenuItem(CMenu* Menu, LPCTSTR MenuName) {
int count = Menu->GetMenuItemCount();
for (int i = 0; i < count; i++) {
CString str;
if (Menu->GetMenuString(i, str, MF_BYPOSITION) &&
str.Compare(MenuName) == 0)
return i;
}
return -1;
}
Upvotes: 9
Reputation: 67195
It appears the answer is that you can't. Using command IDs to locate a menu command makes great sense because such code will continue to work as you rearrange menu items. However, menu items that are sub menus simply do not have a command ID.
One approach is to have a known menu command, which you can search for by ID, and then insert new items next to that command. However, you still need the containing menu.
The approach I ended up using resulted from studying the code MFC uses to populate the most recently used file list in the File menu. The general technique is described in the somewhat dated Paul DiLascia's Q & A column from Microsoft Systems Journal.
Upvotes: 3