0

how to set check on menu item mfc c++ i try this but, always unchecked menu item.

CString tcBuff; 
    CMenu popMenu;
    popMenu.LoadMenu(nMenuID);

    if (text.Compare(defaultconfig) == 0)
    {

        tcBuff.LoadStringW(IDC_DEFAULTREMOVE);
        popMenu.ModifyMenuW(ID_CONFIGURATION_DEFAULT,0,ID_CONFIGURATION_DEFAULT,tcBuff);
        popMenu.CheckMenuItem(IDC_DEFAULTREMOVE, MF_CHECKED || MF_BYCOMMAND);
    }

thanks for help.

nidhal
  • 1,609
  • 4
  • 16
  • 15
  • 1
    You're modifying a new `CMenu` object, rather than the *actual* menu used in your application. Perhaps it's time to pick up [a good book on C++](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and make sure that you understand RAII? – Cody Gray - on strike Dec 22 '11 at 10:00
  • Normally, to check menu items you do not do that. You should use a function handling the your menu item by its ID, using **ON_UPDATE_COMMAND_UI(IDC_DEFAULTREMOVE, function)**. That **function** has a parameter **pCmdUI**. Therefore, you can do **pCmdUI->SetCheck(TRUE);** and **pCmdUI->SetText(tcBuff);** inside your **if** block. – sergiol Jul 14 '15 at 23:21

2 Answers2

1

You want the | operator, not the || operator.

You want to combine the MF_CHECKED and MF_BYCOMMAND bit flags, which you do with a bitwise OR operation. That requires the | operator.

Change your code to look like this:

popMenu.CheckMenuItem(IDC_DEFAULTREMOVE, MF_CHECKED | MF_BYCOMMAND);


The || operator is the logical OR operator. It actually gives you this:

0x8 /* MF_CHECKED */  ||  0x0 /* MF_BYCOMMAND */ == 0

Which is equivalent to MF_UNCHECKED.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • 1
    @nidhal: Another possibility (and the one I first saw) is that you are creating and modifying a *new* `CMenu` object, which gets destroyed automatically as soon as it goes out of scope. You need to be modifying the *actual* menu in your application. There's not enough code posted in the question to actually see what is happening. Lots of variables are being used that are not declared. – Cody Gray - on strike Dec 22 '11 at 09:24
0

Try to use ID_CONFIGURATION_DEFAULT instead of IDC_DEFAULTREMOVE in the statement popMenu.CheckMenuItem(IDC_DEFAULTREMOVE, MF_CHECKED || MF_BYCOMMAND);

ID_CONFIGURATION_DEFAULT - command ID IDC_DEFAULTREMOVE - string resource ID

Pavel Nazarov
  • 723
  • 6
  • 10