icon_handler.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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, 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)