Creating a submenu

Smarty57 picture Smarty57 · Jan 19, 2012 · Viewed 12.8k times · Source

I want to make a sub menu like this Mozilla Firefox sub menu:

Firefox->View->Toolbars

This is what it is like now (in my program):

Program->Menu->Sub Menu

But I want it to look like Firefox were it has an additional menu when you have your mouse over it.

#define ID_SM 1

LRESULT CALLBACK WindowProcedure (HWND hwnd,
                                  UINT message,
                                  WPARAM wParam,
                                  LPARAM lParam)
{
    switch (message)
    {
        case WM_CREATE:
            HMENU hMenubar = CreateMenu();
            HMENU hMenu = CreateMenu();

            AppendMenu(hMenubar, MF_POPUP, (UINT_PTR)hMenu, "Menu");
            AppendMenu(hMenu, MF_STRING, ID_SM, "Sub Menu");

            /* Would I put it here? How? */

            SetMenu(hwnd, hMenubar);
            break;

        case WM_COMMAND:
            if (LOWORD(wParam) == ID_SM) {
                /* Not sure if this should be here,
                   cause I want it to pop up when you mouse over */
            } 
            break;
    }
}

Answer

Cody Gray picture Cody Gray · Jan 20, 2012

You just create another menu and append it as a sub-menu. You can do this by calling the same AppendMenu function, you just need to set the uFlags parameter to MF_POPUP and pass the handle to the submenu as the uIDNewItem parameter.

For example, something like:

case WM_CREATE:
    HMENU hMenubar = CreateMenu();
    HMENU hMenu = CreateMenu();
    HMENU hSubMenu = CreatePopupMenu();

    AppendMenu(hMenubar, MF_POPUP, (UINT_PTR)hMenu, "Menu");
    AppendMenu(hMenu, MF_STRING, ID_SM, "Sub Menu");
    AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT_PTR)hSubMenu, "Sub-Sub Menu");

    SetMenu(hwnd, hMenubar);
    break;

You don't need to do anything special in response to the WM_COMMAND message. Windows will automatically display the pop-up menu when you mouse over the parent menu item. You will, of course, need to handle the commands of the items displayed on the sub-menu, however.