#include <windows.h> #include <shobjidl_core.h> #include <windowsx.h> #include <shlobj_core.h> #pragma comment(lib,"Shell32.lib") #define MAX_LOADSTRING 100 #define SCRATCH_QCM_FIRST 1 #define SCRATCH_QCM_LAST 0x7FFF IContextMenu2* g_pcm2; IContextMenu3* g_pcm3; ... LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int xPos; int yPos; if (g_pcm3) { LRESULT lres; if (SUCCEEDED(g_pcm3->HandleMenuMsg2(message, wParam, lParam, &lres))) { return lres; } } else if (g_pcm2) { if (SUCCEEDED(g_pcm2->HandleMenuMsg(message, wParam, lParam))) { return 0; } } switch (message) { case WM_CONTEXTMENU: { xPos = GET_X_LPARAM(lParam); yPos = GET_Y_LPARAM(lParam); OnContextMenu(hWnd, xPos, yPos); } break; ... void OnContextMenu(HWND hwnd, int xPos, int yPos) { WCHAR pszFilePath[] = L"C:\Users\xx\Desktop\1.txt"; IShellFolder* psfDesktop = NULL; ITEMIDLIST* id = 0; LPCITEMIDLIST idChild = 0; IContextMenu* pcm = NULL; int iCmdTemp = 0; POINT pt = { xPos, yPos }; if (pt.x == -1 && pt.y == -1) { pt.x = pt.y = 0; ClientToScreen(hwnd, &pt); } SHParseDisplayName(pszFilePath, 0, &id, 0, 0); SHBindToParent(id, IID_IShellFolder, (void**)&psfDesktop, &idChild); psfDesktop->GetUIObjectOf(hwnd, 1, (const ITEMIDLIST**)&idChild, __uuidof(IContextMenu), NULL, (void**)&pcm); if (pcm) { HMENU hmenu = CreatePopupMenu(); if (hmenu) { if (SUCCEEDED(pcm->QueryContextMenu(hmenu, 0, SCRATCH_QCM_FIRST, SCRATCH_QCM_LAST, CMF_NORMAL))) { pcm->QueryInterface(IID_IContextMenu2, (void**)&g_pcm2); pcm->QueryInterface(IID_IContextMenu3, (void**)&g_pcm3); int iCmd = TrackPopupMenuEx(hmenu, TPM_RETURNCMD, pt.x, pt.y, hwnd, NULL); if (g_pcm2) { g_pcm2->Release(); g_pcm2 = NULL; } if (g_pcm3) { g_pcm3->Release(); g_pcm3 = NULL; } if (iCmd > 0) { CMINVOKECOMMANDINFOEX info = { 0 }; info.cbSize = sizeof(info); info.fMask = 0x00004000; info.hwnd = hwnd; iCmdTemp = iCmd - SCRATCH_QCM_FIRST; info.lpVerb = MAKEINTRESOURCEA(iCmdTemp); info.lpVerbW = MAKEINTRESOURCEW(iCmdTemp); info.nShow = SW_SHOWNORMAL; pcm->InvokeCommand((LPCMINVOKECOMMANDINFO)&info); } } DestroyMenu(hmenu); } pcm->Release(); } }
相关:How to host an IContextMenu, part 5 – Handling menu messages