I made a quick decision for you. add these units to the Usage section:
... ShlObj, ActiveX, ComObj
and here is your procedure, I just add a new parameter "HND" to transfer the TWinControl handle, which you will use to display the context menu.
procedure ShowSysPopup(aFile: string; x, y: integer; HND: HWND); var Root: IShellFolder; ShellParentFolder: IShellFolder; chEaten,dwAttributes: ULONG; FilePIDL,ParentFolderPIDL: PItemIDList; CM: IContextMenu; Menu: HMenu; Command: LongBool; ICM2: IContextMenu2; ICI: TCMInvokeCommandInfo; ICmd: integer; P: TPoint; Begin OleCheck(SHGetDesktopFolder(Root));//Get the Desktop IShellFolder interface OleCheck(Root.ParseDisplayName(HND, nil, PWideChar(WideString(ExtractFilePath(aFile))), chEaten, ParentFolderPIDL, dwAttributes)); // Get the PItemIDList of the parent folder OleCheck(Root.BindToObject(ParentFolderPIDL, nil, IShellFolder, ShellParentFolder)); // Get the IShellFolder Interface of the Parent Folder OleCheck(ShellParentFolder.ParseDisplayName(HND, nil, PWideChar(WideString(ExtractFileName(aFile))), chEaten, FilePIDL, dwAttributes)); // Get the relative PItemIDList of the File ShellParentFolder.GetUIObjectOf(HND, 1, FilePIDL, IID_IContextMenu, nil, CM); // get the IContextMenu Interace for the file if CM = nil then Exit; PX := X; PY := Y; Windows.ClientToScreen(HND, P); Menu := CreatePopupMenu; try CM.QueryContextMenu(Menu, 0, 1, $7FFF, CMF_EXPLORE or CMF_CANRENAME); CM.QueryInterface(IID_IContextMenu2, ICM2); //To handle submenus. try Command := TrackPopupMenu(Menu, TPM_LEFTALIGN or TPM_LEFTBUTTON or TPM_RIGHTBUTTON or TPM_RETURNCMD, pX, pY, 0, HND, nil); finally ICM2 := nil; end; if Command then begin ICmd := LongInt(Command) - 1; FillChar(ICI, SizeOf(ICI),
change / add initialization section, completion like this
initialization OleInitialize(nil); finalization OleUninitialize;
and here, how you can use this procedure:
procedure TForm2.Button1Click(Sender: TObject); begin ShowSysPopup(Edit1.Text,Edit1.Left,Edit1.Top, Handle); end;
I hope this works for you.
Hi,
Edit: if you want to show a context menu for more than one file, mark this article on your blog