Menus in the Windows Shell
The Windows shell provides a rich set of menu APIs that allow developers to create, modify, and display menus in Explorer extensions and desktop applications. This guide covers the fundamentals of menu management, including creation, insertion, and handling of menu commands.
1. Overview
Menus are represented by the HMENU
handle. You can build standard menu bars, popup menus, context menus, and system menus using the Win32 API functions.
2. Creating a Menu
#include <windows.h>
// Create an empty menu
HMENU hMenu = CreateMenu(); // for a menu bar
HMENU hPopup = CreatePopupMenu(); // for a context menu
3. Adding Items
Use AppendMenu
or InsertMenuItem
to add commands, separators, or submenus.
// Append a simple command
AppendMenu(hMenu, MF_STRING, IDM_FILE_NEW, L"&New");
// Add a separator
AppendMenu(hMenu, MF_SEPARATOR, 0, NULL);
// Add a submenu
HMENU hSub = CreatePopupMenu();
AppendMenu(hSub, MF_STRING, IDM_HELP_ABOUT, L"&About");
AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT_PTR)hSub, L"&Help");
4. Displaying a Menu
For context menus, call TrackPopupMenuEx
with the appropriate flags.
POINT pt;
GetCursorPos(&pt);
TrackPopupMenuEx(hPopup,
TPM_RIGHTBUTTON | TPM_LEFTALIGN,
pt.x, pt.y,
hWnd, NULL);
5. Handling Commands
Process menu selections in the window procedure using WM_COMMAND
.
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDM_FILE_NEW:
// TODO: handle New
break;
case IDM_HELP_ABOUT:
MessageBox(hWnd, L"Sample Application", L"About", MB_OK);
break;
}
break;
// other messages...
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
6. Advanced Topics
- Dynamic menu population based on context.
- Owner-drawn menus for custom visuals.
- Shell extension integration using
IContextMenu
.
7. Sample Project
Download the complete sample from the samples repository. The project demonstrates a basic file explorer extension that adds custom commands to the right‑click menu of files.