Displaying an Item's Context Menu

The ENUMDESK sample supports context menus for items in the tree view and list view controls. Figure 14-4 shows the context menu displayed when I right-click the Nancycl2 [C:] folder.

Figure 14-4.

The context menu for the Nancycl2 [C:] folder in the ENUMDESK sample.

When an application determines that the user has right-clicked a specific tree view or list view item, the application calls a helper function to display the item's context menu. The helper function is passed the handle to the parent window, a pointer to the folder, a pointer to the item ID list, and the location where the context menu should be displayed.

BOOL CMfcenumView::DoTheMenuThing (
HWND hwnd, LPSHELLFOLDER lpsfParent, LPITEMIDLIST lpi, LPPOINT lppt)
{
LPCONTEXTMENU lpcm;
HRESULT hr;
char szTemp [64];
CMINVOKECOMMANDINFO cmi;
DWORD dwAttribs = 0;
int idCmd;
HMENU hMenu;
BOOL bSuccess = TRUE;

hr = lpsfParent->GetUIObjectOf (
hwnd,
1, // get attributes for this many objects
(const struct _ITEMIDLIST **)&lpi,
IID_IContextMenu,
0,
(LPVOID *)&lpcm);

if (SUCCEEDED (hr))
{
hMenu = CreatePopupMenu ();

if (hMenu)
{
// Get the context menu for the item.
hr = lpcm->QueryContextMenu (hMenu, 0, 1, 0x7fff, CMF_EXPLORE);
if (SUCCEEDED (hr))
{
idCmd = TrackPopupMenu (
hMenu, TPM_LEFTALIGN | TPM_RETURNCMD | TPM_RIGHTBUTTON,
lppt->x, lppt->y, 0, hwnd, NULL);

if (idCmd)
{
// Execute the command that was selected.
cmi.cbSize = sizeof (CMINVOKECOMMANDINFO);
cmi.fMask = 0;
cmi.hwnd = hwnd;
cmi.lpVerb = MAKEINTRESOURCE (idCmd - 1);
cmi.lpParameters = NULL;
cmi.lpDirectory = NULL;
cmi.nShow = SW_SHOWNORMAL;
cmi.dwHotKey = 0;
cmi.hIcon = NULL;

hr = lpcm->InvokeCommand (&cmi);
if (! SUCCEEDED (hr))
{
wsprintf (szTemp, "InvokeCommand failed. hr = %lx", hr);
AfxMessageBox (szTemp);
}
}
}

else
bSuccess = FALSE;

DestroyMenu (hMenu);
}

else
bSuccess = FALSE;

lpcm->Release ();
}

else
{
wsprintf (szTemp, "GetUIObjectOf failed! hr = %lx", hr);
AfxMessageBox (szTemp);
bSuccess = FALSE;
}

return bSuccess;
}

With this code in place, the user can right-click an item, view the item's context menu, and choose a command from the context menu.