Displaying a Context Menu for a File 

This code, when used with SHGetIDListFromPath can be used to provide the same popup menu as Explorer for a given file or folder. There is one problem however - the "Send To" menu doesn't load properly (I usually have NotePad in Send To to quickly view text, Delphi or C++ files and not having anything there can be annoying). If anyone knows a fix...

 
procedure ContextMenuForFile(Folder: IShellFolder; Pidl: pItemIDList);
var aContextMenu: IContextMenu;
    aPrgOut: Pointer;
    aPopup: hMenu;
    aCmd: Integer;
    aCmdInfo: TCMInvokeCommandInfo;
    MenuInfo: TMenuItemInfo;
    t, ItemCount: integer;
    buf: array[0..80] of Char;
    Where: TPoint;
begin
  GetCursorPos(Where);
  OLECheck(Folder.GetUIObjectOf(Application.MainForm.Handle, 1, Pidl, IID_IContextMenu,
           aPrgOut, Pointer(aContextMenu)));

  aPopup := CreatePopUpMenu;
  if aPopup = 0 then exit;

  try
    OLECheck(aContextMenu.QueryContextMenu(aPopup, 0, 1, $7FFF, CMF_NORMAL));
    aCmd := Integer(TrackPopupMenuEx(aPopup,  TPM_LEFTALIGN or TPM_RETURNCMD or
                    TPM_RIGHTBUTTON or TPM_HORIZONTAL or TPM_VERTICAL, Where.X, Where.Y,
                    Application.MainForm.Handle, nil));
    if aCmd <> 0 then
    begin
      Fillchar(aCmdInfo, Sizeof(aCmdInfo), 0);
      with aCmdInfo do
      begin
        cbSize := SizeOf(TCMInvokeCommandInfo);
        hwnd   := Application.MainForm.Handle;
        lpVerb := MakeIntResource(aCmd - 1);
        nShow  := SW_SHOWNORMAL;
      end;

      try
        aContextMenu.InvokeCommand(aCmdInfo);
      except
        raise Exception.Create('The system menu for this file could not be created.');
      end;
    end;
  finally
   DestroyMenu(aPopup);
  end;
end;
 
 

The following is an example of using SHGetIDListFromPath and ContextMenuForFile.

procedure DisplayContextMenuForFile(FileName: string);
var ShellFolder: IShellFolder;
    Pidl: pItemIDList;
begin
  Pidl := SHGetIDListFromPath(FileName, ShellFolder);
  if Assigned(Pidl) then
    ContextMenuForFile(ShellFolder, Pidl);
end;
 

Return to the Main Page


This page was created by Ashley Godfrey, 1998.
Borland Delphi is a registered trademark of Inprise Corporation
Window's 95 and Internet Explorer are registered trademarks of Microsoft Corporation
All other products and logos are the property of theor respective owners
Inprise Corporation is in no way affiliated with Ashley Godfrey, this site or any of his software.