2009-12-14

MFC动态生成子菜单

//假设要在pMenu上添加一级子菜单,菜单内容在数组aAllName中,bCheckStyle决定是否为勾选性质的子菜单
    pMenu->CreatePopupMenu();
    for(int i = 0; i < aAllName.GetSize(); i++)
    {
        pMenu->AppendMenu(bCheckStyle ? (((aAllName[i].CompareNoCase(strActive) == 0) ? MF_CHECKED : MF_UNCHECKED) | MF_POPUP) : MF_POPUP, uiIDParentMenu + i, aAllDesc[i]);
    }
//......

//点击某个子菜单响应,如果是bCheckStyle则调整当前的选择项
        if(bCheckStyle)
        {
            for(i = 0; i < pMenu->GetMenuItemCount(); i++)
            {
                //pMenu->CheckMenuItem(i, ((i == iIndex) ? MF_CHECKED : MF_UNCHECKED) | MF_BYPOSITION);
                //如果有 MF_SEPARATOR ,则 MF_BYPOSITION 不对
                pMenu->CheckMenuItem(i + uiIDParentMenu, ((i == iIndex) ? MF_CHECKED : MF_UNCHECKED) | MF_BYCOMMAND);
            }
        }
/*如上注释所示:如果子菜单创建时没有添加MF_SEPARATOR,即子菜单i的POSITION == ParentID + i,则MF_BYPOSITION可以;但是,如果有MF_SEPARATOR,则子菜单i的POSITION != ParentID + i,只能用MF_BYCOMMAND。类似的,EnableMenuItem也是一样:
        //m_mSubMenuRule.EnableMenuItem(i, MF_BYPOSITION | MF_ENABLED);
        m_mSubMenuRule.EnableMenuItem(i + IDM_SELECT_RULE, MF_BYCOMMAND | MF_ENABLED);
*/

No comments: