Getting a custom right-click menu for the caption icon

Raymond Chen

Explorer does it. Now you can too.

It’s a simple matter of detecting a context menu on the caption icon and displaying a custom context menu. Here are the simple changes to our scratch program to display a rather pointless one-item menu.

// Add to WndProc
    case WM_CONTEXTMENU:
        if (lParam != -1 &&
            SendMessage(hwnd, WM_NCHITTEST,
                        0, lParam) == HTSYSMENU) {
            HMENU hmenu = CreatePopupMenu();
            if (hmenu) {
                AppendMenu(hmenu, MF_STRING, 1,
                           TEXT("Custom menu"));
                TrackPopupMenu(hmenu, TPM_LEFTALIGN | TPM_TOPALIGN |
                                      TPM_RIGHTBUTTON,
                               GET_X_LPARAM(lParam),
                               GET_Y_LPARAM(lParam), 0, hwnd, NULL);
                DestroyMenu(hmenu);
            }
            return 0;
        }
        break;

When we receive a WM_CONTEXTMENU message, we check that it did not come from the keyboard (lParam != -1) and that the mouse is on the caption icon (called HTSYSMENU because it displays the system menu by default). If so, then we create a little popup menu and display it. Don’t forget to return 0 instead of passing the message to DefWindowProc, because the default behavior is to display the system menu.

Of course, in real life, you probably would use LoadMenu to get the menu so you could just use the resource editor to create it, rather than creating it in code.

0 comments

Discussion is closed.

Feedback usabilla icon