Using Floating Pop-up Menus

Usually, pop-up menus are “attached” to another menu; they appear when the user selects a command on that menu. However, Windows also lets you provide “floating” pop-up menus, which appear at the current cursor position when the user presses a certain key or clicks a mouse button.

To provide 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 depresses the right mouse button:

POINT currentpoint;

.

.

.

case WM_RBUTTONDOWN:

{

HWND hWnd; /* handle to current window */

HMENU hFloatingPopup; /* handle for floating pop-up */

1 currentpoint = MAKEPOINT (lParam);

/* point at which the user

pressed the button */

.

.

.

2 hFloatingPopup = CreatePopupMenu();

3 AppendMenu (hFloatingPopup,

MF_ENABLED,

IDM_CALC,

“Calculator”);

AppendMenu (hFloatingPopup,

MF_ENABLED,

IDM_CARDFILE,

“Cardfile”);

AppendMenu (hFloatingPopup,

MF_ENABLED,

IDM_NOTEPAD,

“Notepad”);

4 ClientToScreen (hWnd, (LPPOINT)&currentpoint);

5 TrackPopupMenu (hFloatingPopup,

NULL,

6 currentpoint.x,

currentpoint.y,

NULL,

hWnd,

NULL);

7 DestroyMenu (hFloatingPopup);

break;

}

In this example:

1 The lParam parameter of the WM_RBUTTONDOWN message contains the current position of the mouse. The MAKEPOINT function converts this long value to a point, which is then stored in the currentpoint data structure.
2 The CreatePopupMenu function creates an empty pop-up menu, and returns a handle to that menu. The new menu's handle is placed in the variable hFloatingPopup.
3 After creating the empty pop-up menu, the application appends three items to it: Calculator, Cardfile, and Notepad.
4 The ClientToScreen function converts the coordinates of the current cursor position so that they describe the position relative to the entire screen's upper-left corner. (Initially, the coordinates describe the cursor position relative to the client window instead).
5 Once the menu is complete, the application displays it at the current cursor position by calling TrackPopupMenu.
6 The x and y fields of the currentpoint data structure contain the current screen coordinates of the cursor.
7 After the user has made a selection from the menu, the application destroys the menu, thereby freeing up the memory the menu used. The application re-creates the menu each time the user depresses the right mouse button.