Get the associated file icon for a file

What I want

I am trying to write a function that takes a filename and returns the icon of the application associated with the file type of the file on my system (this is Windows 7).

What i tried

I've seen this question , but the answer doesn't give me the details I need. I'm not very familiar with the ctypes module, and I find the docs on VC ++ functions difficult to follow.

I've seen this question as well , but I'm stuck at the first hurdle. When I try:

import _winreg
_winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\Microsoft\CurrentVersion\Explorer\FileExts')

      

Raises WindowsError: [Error 2] The system cannot find the file specified

Even when i do

_winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\Microsoft')

      

Which returns a PyHKEY object

, any "key" action I try to do calls aTypeError: The object is not a PyHKEY object

+3


source to share


1 answer


I found the answer here

code from link:



import win32ui
import win32gui
import win32con
import win32api
import cStringIO
import Image

tempDirectory = os.getenv("temp")
ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON)

dst = cStringIO.StringIO()

large, small = win32gui.ExtractIconEx(path,0)
win32gui.DestroyIcon(small[0])

#creating a destination memory DC
hdc = win32ui.CreateDCFromHandle( win32gui.GetDC(0) )
hbmp = win32ui.CreateBitmap()
hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_x)
hdc = hdc.CreateCompatibleDC()

hdc.SelectObject( hbmp )

#draw a icon in it
hdc.DrawIcon( (0,0), large[0] )
win32gui.DestroyIcon(large[0])

#convert picture
hbmp.SaveBitmapFile( hdc, tempDirectory + "\Icontemp.bmp")

im = Image.open(tempDirectory + "\Icontemp.bmp")
im.save(dst, "JPEG")

dst.seek(0)

os.remove(tempDirectory + "\Icontemp.bmp")    
return dst.read()

      

-1


source







All Articles