copy_hook.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # A sample shell copy hook.
  2. # To demostrate:
  3. # * Execute this script to register the context menu.
  4. # * Open Windows Explorer
  5. # * Attempt to move or copy a directory.
  6. # * Note our hook's dialog is displayed.
  7. import sys, os
  8. import pythoncom
  9. from win32com.shell import shell, shellcon
  10. import win32gui
  11. import win32con
  12. import winerror
  13. # Our shell extension.
  14. class ShellExtension:
  15. _reg_progid_ = "Python.ShellExtension.CopyHook"
  16. _reg_desc_ = "Python Sample Shell Extension (copy hook)"
  17. _reg_clsid_ = "{1845b6ba-2bbd-4197-b930-46d8651497c1}"
  18. _com_interfaces_ = [shell.IID_ICopyHook]
  19. _public_methods_ = ["CopyCallBack"]
  20. def CopyCallBack(self, hwnd, func, flags,
  21. srcName, srcAttr, destName, destAttr):
  22. # This function should return:
  23. # IDYES Allows the operation.
  24. # IDNO Prevents the operation on this folder but continues with any other operations that have been approved (for example, a batch copy operation).
  25. # IDCANCEL Prevents the current operation and cancels any pending operations.
  26. print "CopyCallBack", hwnd, func, flags, srcName, srcAttr, destName, destAttr
  27. return win32gui.MessageBox(hwnd, "Allow operation?", "CopyHook",
  28. win32con.MB_YESNO)
  29. def DllRegisterServer():
  30. import _winreg
  31. key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT,
  32. "directory\\shellex\\CopyHookHandlers\\" +
  33. ShellExtension._reg_desc_)
  34. _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, ShellExtension._reg_clsid_)
  35. key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT,
  36. "*\\shellex\\CopyHookHandlers\\" +
  37. ShellExtension._reg_desc_)
  38. _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, ShellExtension._reg_clsid_)
  39. print ShellExtension._reg_desc_, "registration complete."
  40. def DllUnregisterServer():
  41. import _winreg
  42. try:
  43. key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,
  44. "directory\\shellex\\CopyHookHandlers\\" +
  45. ShellExtension._reg_desc_)
  46. except WindowsError, details:
  47. import errno
  48. if details.errno != errno.ENOENT:
  49. raise
  50. try:
  51. key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,
  52. "*\\shellex\\CopyHookHandlers\\" +
  53. ShellExtension._reg_desc_)
  54. except WindowsError, details:
  55. import errno
  56. if details.errno != errno.ENOENT:
  57. raise
  58. print ShellExtension._reg_desc_, "unregistration complete."
  59. if __name__=='__main__':
  60. from win32com.server import register
  61. register.UseCommandLine(ShellExtension,
  62. finalize_register = DllRegisterServer,
  63. finalize_unregister = DllUnregisterServer)
  64. #!/usr/bin/env python