/venv/Lib/site-packages/win32comext/shell/demos/servers/icon_handler.py

https://bitbucket.org/fox06/updatesprocessor
Python | 70 lines | 49 code | 9 blank | 12 comment | 6 complexity | 52abecec3c5c642277bf7181d679e08f MD5 | raw file
  1. # A sample icon handler. Sets the icon for Python files to a random
  2. # ICO file. ICO files are found in the Python directory - generally there will
  3. # be 3 icons found.
  4. #
  5. # To demostrate:
  6. # * Execute this script to register the context menu.
  7. # * Open Windows Explorer, and browse to a directory with a .py file.
  8. # * Note the pretty, random selection of icons!
  9. import sys, os
  10. import pythoncom
  11. from win32com.shell import shell, shellcon
  12. import win32gui
  13. import win32con
  14. import winerror
  15. # Use glob to locate ico files, and random.choice to pick one.
  16. import glob, random
  17. ico_files = glob.glob(os.path.join(sys.prefix, "*.ico"))
  18. if not ico_files:
  19. ico_files = glob.glob(os.path.join(sys.prefix, "PC", "*.ico"))
  20. if not ico_files:
  21. print("WARNING: Can't find any icon files")
  22. # Our shell extension.
  23. IExtractIcon_Methods = "Extract GetIconLocation".split()
  24. IPersistFile_Methods = "IsDirty Load Save SaveCompleted GetCurFile".split()
  25. class ShellExtension:
  26. _reg_progid_ = "Python.ShellExtension.IconHandler"
  27. _reg_desc_ = "Python Sample Shell Extension (icon handler)"
  28. _reg_clsid_ = "{a97e32d7-3b78-448c-b341-418120ea9227}"
  29. _com_interfaces_ = [shell.IID_IExtractIcon, pythoncom.IID_IPersistFile]
  30. _public_methods_ = IExtractIcon_Methods + IPersistFile_Methods
  31. def Load(self, filename, mode):
  32. self.filename = filename
  33. self.mode = mode
  34. def GetIconLocation(self, flags):
  35. # note - returning a single int will set the HRESULT (eg, S_FALSE,
  36. # E_PENDING - see MS docs for details.
  37. return random.choice(ico_files), 0, 0
  38. def Extract(self, fname, index, size):
  39. return winerror.S_FALSE
  40. def DllRegisterServer():
  41. import winreg
  42. key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT,
  43. "Python.File\\shellex")
  44. subkey = winreg.CreateKey(key, "IconHandler")
  45. winreg.SetValueEx(subkey, None, 0, winreg.REG_SZ, ShellExtension._reg_clsid_)
  46. print(ShellExtension._reg_desc_, "registration complete.")
  47. def DllUnregisterServer():
  48. import winreg
  49. try:
  50. key = winreg.DeleteKey(winreg.HKEY_CLASSES_ROOT,
  51. "Python.File\\shellex\\IconHandler")
  52. except WindowsError as details:
  53. import errno
  54. if details.errno != errno.ENOENT:
  55. raise
  56. print(ShellExtension._reg_desc_, "unregistration complete.")
  57. if __name__=='__main__':
  58. from win32com.server import register
  59. register.UseCommandLine(ShellExtension,
  60. finalize_register = DllRegisterServer,
  61. finalize_unregister = DllUnregisterServer)