当用户按下F1键时,我正在尝试覆盖对话窗口的WM_HELP消息。该窗口有几个按钮,通过TrackPopupMenu显示上下文菜单,以及主菜单(在顶部。)因此,此窗口中不仅仅有一个菜单。
我可以在处理WM_HELP
时捕获菜单消息,但我需要知道发送此消息的上下文菜单:
BOOL CMyDialog::OnHelpInfo(HELPINFO* pHelpInfo)
{
if(pHelpInfo->iContextType == HELPINFO_MENUITEM)
{
HMENU hMenu = (HMENU)pHelpInfo->hItemHandle;
//How to get menu ID from HMENU?
}
//...
}
所以我需要找到一种从HMENU
获取菜单资源ID的方法 - 这个用于创建它的那个:
知道该怎么做吗?
答案 0 :(得分:2)
你必须“有点暴力”。你可以从上到下接近它。做一个像这样的函数:
BOOL IsMenuItemIDInMenu(UINT nMenuID, UINT nMenuItemID)
{
//Checks if 'nMenuItemID' belongs to 'nMenuID'
BOOL bRes = FALSE;
if(nMenuID &&
nMenuItemID)
{
HMENU hMenu = ::LoadMenu(GetModuleHandle(NULL), MAKEINTRESOURCE(nMenuID));
if(hMenu)
{
//Look for it
bRes = __searchForMenuItem(hMenu, nMenuItemID);
//Free menu
::DestroyMenu(hMenu);
}
}
return bRes;
}
BOOL __searchForMenuItem(HMENU hMenu, UINT nMenuItemID)
{
ASSERT(hMenu);
int nCnt = ::GetMenuItemCount(hMenu);
if(nCnt != -1)
{
for(int i = 0; i < nCnt; i++)
{
//Is it a submenu
HMENU hSubMenu = ::GetSubMenu(hMenu, i);
if(!hSubMenu)
{
UINT nID = ::GetMenuItemID(hMenu, i);
if(nID != -1 &&
nID == nMenuItemID)
{
//Found it
return TRUE;
}
}
else
{
//Process submenu
if(__searchForMenuItem(hSubMenu, nMenuItemID))
{
//Found it in submenu
return TRUE;
}
}
}
}
return FALSE;
}
然后当您获得按下F1时突出显示的菜单ID时,请查看它属于哪个菜单:
if(pHelpInfo->iContextType == HELPINFO_MENUITEM)
{
if(IsMenuItemIDInMenu(IDR_MENU_1, pHelpInfo->iCtrlId))
{
}
else if(IsMenuItemIDInMenu(IDR_MENU_2, pHelpInfo->iCtrlId))
{
}
}