Want to change the default program & icon depend on the file extension in windows 10.
Is there a library can do this?
Not directly, but the information is in the registry (sometimes known as regedit.exe). Python on Windows has a winreg
module that can be used to access the registry.
This StackOverflow answer briefly describes what values you need to modify to change the icon. The default program setting is next to it, under UserChoice
.
Directly modifying the HKCR pseudo-key is generally a bad idea. Since Windows 2000, this pseudo-key is implemented as a merged view of the “Software\Classes” keys in the user (HKCU) and machine (HKLM) hives. It’s best to work with this view as if it’s read-only, even though in practice that’s not enforced. User keys take precedence over machine keys in the view, so an operation to modify a subkey relative to HKCR might modify either a user setting or a system setting, depending on the keys that already exist. You should know exactly what you need to change at the system level in “HKLM\Software\Classes” or just for the current user in “HKCU\Software\Classes”. If you don’t know at least this, then you shouldn’t be changing anything at all.
After modifying the ProgId in the registry, you should notify the shell to make it reload the file association. For example:
>>> import ctypes
>>> shell32 = ctypes.OleDLL('shell32')
>>> shell32.SHChangeNotify.restype = None
>>> event = SHCNE_ASSOCCHANGED = 0x08000000
>>> flags = SHCNF_IDLIST = 0x0000
>>> shell32.SHChangeNotify(event, flags, None, None)
The shell’s “UserChoice” value was added in Windows 7. It gets set when the user selects to always open a file type with a given application. The shell (Explorer) stores this setting in a subkey of “HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts”, instead of in the user’s software classes hive. This key is not documented in the Windows API. Programs should instead call AssocQueryStringW
to look up the associated ProgId for a given file type. For example:
>>> import ctypes
>>> shlwapi = ctypes.OleDLL('shlwapi')
>>> flags = ASSOCF_INIT_IGNOREUNKNOWN = 0x00000400
>>> astr = ASSOCSTR_PROGID = 20
>>> cch = ctypes.c_ulong()
>>> shlwapi.AssocQueryStringW(flags, astr, ".py", None, None, ctypes.byref(cch))
1
>>> sz = (ctypes.c_wchar * cch.value)()
>>> shlwapi.AssocQueryStringW(flags, astr, ".py", None, sz, ctypes.byref(cch))
0
>>> sz.value
'Python.File'