7.6.3 Using Floating Pop-up Menus

Usually, pop-up menus are attached to another menu—that is, they appear when the user chooses a command on that menu. With Windows, however, you can also provide pop-up menus that float, which means they appear at the current cursor position when the user presses a certain key or clicks a mouse button.

To create a floating pop-up menu, you use the CreatePopupMenu and TrackPopupMenu functions. If you want the floating pop-up menu to appear when the user presses a certain key or mouse button, create the floating pop-up menu within the case statement that handles the input message from that key or button.

The following example displays a floating pop-up menu when the user presses the left mouse button:

        case WM_LBUTTONDOWN:
            GetClientRect(hWnd, (LPRECT)&rc);
            if (PtInRect((LPRECT)&rc, MAKEPOINT(lParam)))
                HandlePopupMenu(hWnd, MAKEPOINT(lParam));
            break;
            .
            .
            .






void FAR PASCAL HandlePopupMenu(hwnd, point)
HWND   hwnd;
POINT  point;

{
    HMENU hMenu;
    HMENU hMenuTrackPopup;

    /* Get the menu for the pop-up menu from the resource file. */

    hMenu = LoadMenu(hInst, "PopupMenu");
    if (!hMenu)
        return;

    /*
     * Get the first menu in the pop-up menu to use in the call
     * to TrackPopupMenu. This could also have been created by
     * using CreatePopupMenu and then added by using InsertMenu
     * or AppendMenu.
     */

    hMenuTrackPopup = GetSubMenu(hMenu, 0);

    /*
     * Convert the mouse point to screen coordinates, because that
     * is what TrackPopup expects.
     */

    ClientToScreen(hwnd, (LPPOINT)&point);

    /* Draw and track the "floating" pop-up menu. */

    TrackPopupMenu(hMenuTrackPopup, 0, point.x, point.y, 0, hwnd, NULL);

    DestroyMenu(hMenu);
}

In this example, the lParam parameter of the WM_LBUTTONDOWN message contains the current position of the mouse. The MAKEPOINT macro converts this long value to a point, which is then stored in the currentpoint structure.

Once the menu is complete, the application displays it at the current cursor position by calling TrackPopupMenu. (The x and y members of the currentpoint structure specify the current position of the cursor.)

After the user has chosen a command from the menu, the application destroys the menu, freeing the memory the menu used. The application re-creates the menu each time the user presses the right mouse button.