为什么DefaultIcon注册表设置不起作用(Python / winreg)

时间:2015-05-15 20:19:58

标签: python windows registry winreg

以下代码旨在根据我对注册表设置的了解,为文件类型设置默认图标和默认应用程序。我可以看到使用regedit进行更改,但具有该扩展名的文件的信息不会更改。有关如何做到这一点的任何建议吗?

import os.path
import _winreg as winreg

G2path="Z:\\Scratch\\GSASII"
G2icon = 'c:\\gsas2.ico,0'
G2bat = os.path.join(G2path,'RunGSASII.bat')

gpxkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER,r'Software\CLASSES\.gpx')
#gpxkey = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, '.gpx')
iconkey = winreg.CreateKey(gpxkey, 'DefaultIcon')
winreg.SetValue(iconkey, None, winreg.REG_SZ, G2icon)
openkey = winreg.CreateKey(gpxkey, 'OpenWithList')
g2key = winreg.CreateKey(openkey, 'GSAS-II')
winreg.SetValue(g2key, None, winreg.REG_SZ, G2bat)

winreg.CloseKey(iconkey)
winreg.CloseKey(g2key)
winreg.CloseKey(openkey)
#winreg.CloseKey(gpxkey)
winreg.FlushKey(gpxkey)

1 个答案:

答案 0 :(得分:0)

在这里找到了解决我的图标问题的线索:https://msdn.microsoft.com/en-us/library/windows/desktop/hh127427%28v=vs.85%29.aspx。我需要:

  1. 为我正在创建的密钥设置一个值
  2. 触发shell的更新以查看更改。
  3. 此代码确实可以显示图标:

    import os.path
    import _winreg as winreg
    
    G2path="Z:\\Scratch\\GSASII"
    G2icon = 'c:\\gsas2.ico'
    G2bat = os.path.join(G2path,'RunGSASII.bat')
    
    gpxkey = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, '.gpx')
    winreg.SetValue(gpxkey, None, winreg.REG_SZ, 'GSAS-II project') # what was needed!
    iconkey = winreg.CreateKey(gpxkey, 'DefaultIcon')
    winreg.SetValue(iconkey, None, winreg.REG_SZ, G2icon)    
    winreg.CloseKey(iconkey)
    winreg.CloseKey(gpxkey)
    
    # show the change
    import win32com.shell.shell, win32com.shell.shellcon
    win32com.shell.shell.SHChangeNotify(
        win32com.shell.shellcon.SHCNE_ASSOCCHANGED, 0, None, None)
    

    要获得与扩展相关联的应用程序,我还需要做更多。这有助于:Create registry entry to associate file extension with application in C++

    请注意,正如链接中所建议的那样,我使用HKEY_CURRENT_USER,因为这样可以避免需要admin privs。

    import _winreg as winreg
    
    G2bat = "Z:\\Scratch\\GSASII\\RunGSASII.bat"
    G2icon = 'c:\\gsas2.ico'
    gpxkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER,r'Software\CLASSES\.gpx')
    winreg.SetValue(gpxkey, None, winreg.REG_SZ, 'GSAS-II.project')
    winreg.CloseKey(gpxkey)
    
    gpxkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER,r'Software\CLASSES\GSAS-II.project')
    winreg.SetValue(gpxkey, None, winreg.REG_SZ, 'GSAS-II project')
    
    iconkey = winreg.CreateKey(gpxkey, 'DefaultIcon')
    winreg.SetValue(iconkey, None, winreg.REG_SZ, G2icon)
    openkey = winreg.CreateKey(gpxkey, r'shell\open\command')
    winreg.SetValue(openkey, None, winreg.REG_SZ, G2bat+" %1")
    
    winreg.CloseKey(iconkey)
    winreg.CloseKey(openkey)
    winreg.CloseKey(gpxkey)
    
    import win32com.shell.shell, win32com.shell.shellcon
    win32com.shell.shell.SHChangeNotify(
        win32com.shell.shellcon.SHCNE_ASSOCCHANGED, 0, None, None)