How do I make a boldface item on a context menu?

Raymond Chen

Today’s Little Program displays a context menu with a bold item. I sort of talked about this some time ago, but now I’m going to actually do it. Remember, the boldface item represents the default item. You should set it to the action that would have taken place if the user had double-clicked the object.

Start with our scratch program and make the following changes:

void OnContextMenu(HWND hwnd, HWND hwndContext, UINT xPos, UINT yPos)
 HMENU hmenu = CreatePopupMenu();
 AppendMenu(hmenu, MF_STRING, 100, TEXT("&First"));
 AppendMenu(hmenu, MF_STRING, 101, TEXT("&Second"));
 AppendMenu(hmenu, MF_STRING, 102, TEXT("&Third"));

 SetMenuDefaultItem(hmenu, 101, FALSE);

 TrackPopupMenuEx(hmenu, 0, xPos, yPos, hwnd, nullptr);


    HANDLE_MSG(hwnd, WM_CONTEXTMENU, OnContextMenu);

Note that for expository purposes (this is a Little Program, after all), I am not heeding the advice I gave some time ago. As a result, this program does not support multiple monitors or keyboard-invoked context menus. Read the linked article for instructions on how to fix the code.

When you right-click on the window, the On­Context­Menu function creates a pop-up window, fills it with some dummy commands, and says that item 101 should be the default. Then it displays the context menu to the user, throws away the result, and destroys the menu to avoid a memory leak.

When the menu pops up, the item Second appears in boldface.