Farrukh Sarmad
Farrukh Sarmad

Reputation: 325

How to mark a menu item checked using mfc in vc++ 6?

I created a menu Styles with an item U for underlining with a code:

void CPersonalEditorView::OnStylesU(){
    CHARFORMAT cf; 
    cf.cbSize = sizeof(cf);
    cf.dwMask = CFM_UNDERLINE;
    cf.dwEffects   = CFE_UNDERLINE;
    GetRichEditCtrl().SetSelectionCharFormat(cf);}

I want to mark a check when the "U" menu item is clicked. I have tried:

CMenu *pMenu = GetMenu();
if (pMenu != NULL)
{   
    pMenu->CheckMenuItem(ID_STYLES_U, MF_CHECKED | MF_BYCOMMAND);
}

not worked and:

CWnd* pParent = GetParent();
CMenu* pMenu  = pParent->GetMenu();
pMenu->CheckMenuItem(ID_STYLES_U, MF_CHECKED);

not worked and :

CMenu popupMenu;
popupMenu.LoadMenu(IDR_PERSONTYPE);
popupMenu.CheckMenuItem(ID_STYLES_U,MF_CHECKED);

not worked. Tell me anything that could help me.

Upvotes: 1

Views: 1263

Answers (1)

Andrew Truckle
Andrew Truckle

Reputation: 19087

Display your menu in the resource editor and right-click and select Add Event Handler:

Menu

Next, you need to select the UPDATE_COMMAND_UI message and choose the appropriate class. Then click Add and Edit:

Wizard

Then, you just update the menu item as needed. For example:

void CMainFrame::OnUpdateOptionsLanguageItalian(CCmdUI* pCmdUI) 
{
    pCmdUI->SetCheck( theApp.GetProgramLanguage() == LANGUAGE_ITALIAN ? 1 : 0 );
}

In the above example I am using SetCheck. There are other choices aswell if you look at the class.

If your menu was inside a CDialog then you can't use the above mechanism, because the architecture is not there by default. You could add a lot of the framework but it is not worth it. For a dialog object you create a method and manually call it on demand. In your method you would do:

CMenu *pMenu = GetMenu();

if (pMenu != nullptr)
{
    pMenu->CheckMenuItem(ID_VIEW_ASSIGNMENT_HISTORY,
        (m_pAssignHistoryDlg != nullptr)
        ? MF_BYCOMMAND | MF_CHECKED : MF_BYCOMMAND | MF_UNCHECKED);
}

So now you know both approaches, dependant on the context of your menu.

That said, in your question you don't provide much context about your menu. Is it a popup menu? Is it part of the mainframe? When are you invoking the menu?

Hopefully the above, as indicated in the comment to your question, will suffice.

Upvotes: 1

Related Questions