Wednesday, November 2, 2011

Explorer Context Menu in your App

As I am currently working on C++ project, I learn lots of new things daily. In our project we needed to provide Explorer's Context Menu for our custom built explorer. This requires COM, many C++ programmers know that COM is one of the tough topics from C++ Windows Development. Anyways, this post describes about how to use Explorer's Context Menu in C++ application.

This requires understanding of COM, COM related objects which you can find here.
Following is the code snippet which shows how this can be done.
IShellFolder *psfDesktop;
SHGetDesktopFolder(&psfDesktop);
// Retrieve Desktop's Shell Folder handle
if(psfDesktop)
{
 LPITEMIDLIST pidl;
 BSTR strMyFolderPath = ::SysAllocString(L"C:\\myfolder");
 psfDesktop->ParseDisplayName(hWnd, 0, strMyFolderPath, NULL, &pidl, NULL);
 ::SysFreeString(strMyFolderPath);



  IShellFolder *psfMyFolder;
  LPITEMIDLIST pidlFolder;
  if(SHBindToParent(pidl, IID_IShellFolder, (void**)&psfMyFolder, (LPCITEMIDLIST*)&pidlFolder) == S_OK)
  {
    IContextMenu *pcm;
    psfMyFolder->GetUIObjectOf(hWnd, 1, (LPCITEMIDLIST*)&pidlFolder, IID_IContextMenu, 0, (void**)&pcm);
    if(pcm)
    {
      HMENU hMenu = CreatePopupMenu();
      pcm->QueryContextMenu(hMenu, 0, 1, 0x7ff, CMF_EXPLORE | CMF_NORMAL | MF_EXTENDEDVERBS);

      POINT pt;
      GetCursorPos(&pt);
      int idCmd = TrackPopupMenu(hMenu, TPM_LEFTALIGN | TPM_RETURNCMD, pt.x, pt.y, 0, hWnd, NULL);
      DestroyMenu(hMenu);
      pcm->Release();

    }

    LPMALLOC lpMalloc = NULL;
    SHGetMalloc(&lpMalloc);
    lpMalloc->Free(pidl);
    lpMalloc->Free(pidlFolder);
    lpMalloc->Release();
    psfMyFolder->Release();

  }
 pDesktop->Release();
}

No comments:

Post a Comment

Ads Inside Post