简体   繁体   中英

Set CMenu item prompt at runtime

How can I set a CMenu item prompt at runtime? I know that it can be done in resource editor in VS, but I don't have such resource and create menu and it's items dynamically.

If you are using MFC Feature Pack, you will need to override the OnMenuButtonToolHitTest of your MainFrame class:

BOOL CMainFrame::OnMenuButtonToolHitTest(CMFCToolBarButton* pButton, TOOLINFO* pTI)
{
    if(!pButton)
        return FALSE;
    if(!pTI)
        return FALSE;

    if (pButton->m_nID == UINT(-1)) //not a menu-item, but an opener menu for a sub-menu
        return FALSE;

    // Stolen from CMFCToolBar::OnToolHitTest on file afxtoolbar.cpp

    // It is not needed to do the GetMessageString part, because it already done
    // on function CMFCPopupMenuBar::OnToolHitTest of afxpopupmenubar.cpp file, which
    // supplies the two parts to the Tooltip Manager

    CString strTipText;
    TCHAR szFullText[256];

    AfxLoadString(pButton->m_nID, szFullText);
    AfxExtractSubString(strTipText, szFullText, 1, '\n');

    pTI->lpszText = _tcsdup(strTipText);

    return TRUE;
}

You will have to define in your resource file strings with the EXACT same ID as your menus; and their format is Prompt text\\nPrompt title . I am not sure but I think the only new line you can have is the one that separates title from text.

You may also want to do things beyond simply displaying prompts when hovering menus using the mouse. You can do it by overriding OnMenuSelect of your MainFrame class:

void CMainFrame::OnMenuSelect(UINT nItemID, UINT nFlags, HMENU hSysMenu)
{
    if (nItemID == ID_MENU_I_WANT_TO_PROCESS)
    {
        DoThings(); 
    }

    __super::OnMenuSelect(nItemID, nFlags, hSysMenu);
}

I recommend you to make an override to GetMessageString function on your MainFrame class and put a breakpoint there for you see how the flow goes.

You can use ModifyMenu ( https://msdn.microsoft.com/fr-fr/library/4tbfebs6.aspx ). The call can be something like:

 pParentMenu->ModifyMenu(ID_MY_ITEM, MF_STRING, ID_MY_ITEM, "My new text");

pParentMenu is a CMenu object pointing to the parent menu. ID_MY_ITEM is the sub-menu id. It is also possible to select the menu to change using its index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM