如何使用Delphi弹出给定文件的Windows上下文菜单?

前端之家收集整理的这篇文章主要介绍了如何使用Delphi弹出给定文件的Windows上下文菜单?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想写下面的过程/函数
  1. procedure ShowSysPopup(aFile: string; x,y: integer);

这将构建并显示(在坐标x和y处)右键单击的shell菜单,在Windows资源管理器中可以看到给定文件.我对’显示’部分不是那么感兴趣,而是更多关于如何构建这样的菜单.

解决方法

我为你做了一个快速解决方案.
将这些单位添加到“使用”部分:
  1. ... ShlObj,ActiveX,ComObj

这是你的程序,我只需添加新参数“HND”来携带TWinControl的句柄,你将用它来显示上下文菜单.

  1. procedure ShowSysPopup(aFile: string; x,y: integer; HND: HWND);
  2. var
  3. Root: IShellFolder;
  4. ShellParentFolder: IShellFolder;
  5. chEaten,dwAttributes: ULONG;
  6. FilePIDL,ParentFolderPIDL: PItemIDList;
  7. CM: IContextMenu;
  8. Menu: HMenu;
  9. Command: LongBool;
  10. ICM2: IContextMenu2;
  11.  
  12. ICI: TCMInvokeCommandInfo;
  13. ICmd: integer;
  14. P: TPoint;
  15. Begin
  16. OleCheck(SHGetDesktopFolder(Root));//Get the Desktop IShellFolder interface
  17.  
  18. OleCheck(Root.ParseDisplayName(HND,nil,PWideChar(WideString(ExtractFilePath(aFile))),chEaten,ParentFolderPIDL,dwAttributes)); // Get the PItemIDList of the parent folder
  19.  
  20. OleCheck(Root.BindToObject(ParentFolderPIDL,IShellFolder,ShellParentFolder)); // Get the IShellFolder Interface of the Parent Folder
  21.  
  22. OleCheck(ShellParentFolder.ParseDisplayName(HND,PWideChar(WideString(ExtractFileName(aFile))),FilePIDL,dwAttributes)); // Get the relative PItemIDList of the File
  23.  
  24. ShellParentFolder.GetUIObjectOf(HND,1,IID_IContextMenu,CM); // get the IContextMenu Interace for the file
  25.  
  26. if CM = nil then Exit;
  27. P.X := X;
  28. P.Y := Y;
  29.  
  30. Windows.ClientToScreen(HND,P);
  31.  
  32. Menu := CreatePopupMenu;
  33.  
  34. try
  35. CM.QueryContextMenu(Menu,$7FFF,CMF_EXPLORE or CMF_CANRENAME);
  36. CM.QueryInterface(IID_IContextMenu2,ICM2); //To handle submenus.
  37. try
  38. Command := TrackPopupMenu(Menu,TPM_LEFTALIGN or TPM_LEFTBUTTON or TPM_RIGHTBUTTON or
  39. TPM_RETURNCMD,p.X,p.Y,HND,nil);
  40. finally
  41. ICM2 := nil;
  42. end;
  43.  
  44. if Command then
  45. begin
  46. ICmd := LongInt(Command) - 1;
  47. FillChar(ICI,SizeOf(ICI),#0);
  48. with ICI do
  49. begin
  50. cbSize := SizeOf(ICI);
  51. hWND := 0;
  52. lpVerb := MakeIntResourceA(ICmd);
  53. nShow := SW_SHOWNORMAL;
  54. end;
  55. CM.InvokeCommand(ICI);
  56. end;
  57. finally
  58. DestroyMenu(Menu)
  59. end;
  60. End;

像这样修改/添加初始化,终结部分

  1. initialization
  2. OleInitialize(nil);
  3. finalization
  4. OleUninitialize;

在这里你可以使用这个程序:

  1. procedure TForm2.Button1Click(Sender: TObject);
  2. begin
  3. ShowSysPopup(Edit1.Text,Edit1.Left,Edit1.Top,Handle);
  4. end;

我希望这对你有用.

问候,

编辑:
如果要显示多个文件的上下文菜单,请检查this article in my blog

猜你在找的Delphi相关文章