October 27th, 2003

Getting a custom right-click menu for the caption icon

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.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.

Feedback