Ari Seyhun
Ari Seyhun

Reputation: 12511

Toggle Windows Menu Item Checkbox in C++

I'm trying to toggle the checkbox next to my menu item and also change a bool in my code to correspond with whether the menu item is checked or not.

I have a case in my switch (message) { ... } inside my WndProc function for the specific menu item. I also have a bool variable set to TRUE and my menu item is checked by default.

Here's what I've tried so far:

HMENU hmenu = GetMenu(hWnd);
LPMENUITEMINFO menuItem;
GetMenuItemInfo(hmenu, ID_OPTIONS_COMPUTERDELAY, FALSE, &menuItem);

if (menuItem->fState == MFS_CHECKED) {
    // Checked, uncheck it
    menuItem->fState = MFS_UNCHECKED;
    SetMenuItemInfo(hmenu, ID_OPTIONS_COMPUTERDELAY, FALSE, &menuItem);
} else {
    // Unchecked, check it
    menuItem->fState = MFS_CHECKED;
    SetMenuItemInfo(hmenu, ID_OPTIONS_COMPUTERDELAY, FALSE, &menuItem);
}

I receive the following errors (line numbers were changed to match code above):

Line 3: argument of type "LPMENUITEMINFO *" is incompatible with parameter of type "LPMENUITEMINFOW"
Line 8: argument of type "LPMENUITEMINFO *" is incompatible with parameter of type "LPCMENUITEMINFOW"
Line 12: argument of type "LPMENUITEMINFO *" is incompatible with parameter of type "LPCMENUITEMINFOW"
Line 4: 'BOOL GetMenuItemInfoW(HMENU,UINT,BOOL,LPMENUITEMINFOW)': cannot convert argument 4 from 'LPMENUITEMINFO *' to 'LPMENUITEMINFOW'

Upvotes: 1

Views: 1789

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595377

GetMenuItemInfo() and SetMenuItemInfo() expect a pointer to an allocated MENUITEMINFO instance, but you are passing them a pointer to an uninitialized MENUITEMINFO* pointer instead. That is why you are getting errors.

You also have to set the cbSize and fMask fields before calling GetMenuItemInfo().

Try this instead:

HMENU hmenu = GetMenu(hWnd);

MENUITEMINFO menuItem = {0};
menuItem.cbSize = sizeof(MENUITEMINFO);
menuItem.fMask = MIIM_STATE;

GetMenuItemInfo(hmenu, ID_OPTIONS_COMPUTERDELAY, FALSE, &menuItem);

if (menuItem.fState == MFS_CHECKED) {
    // Checked, uncheck it
    menuItem.fState = MFS_UNCHECKED;
} else {
    // Unchecked, check it
    menuItem.fState = MFS_CHECKED;
}
SetMenuItemInfo(hmenu, ID_OPTIONS_COMPUTERDELAY, FALSE, &menuItem);

Upvotes: 1

Related Questions