March 30th, 2015

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

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);

 DestroyMenu(hmenu);
}

    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.

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.