加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

如何在Windows上使用Python更改文件夹图标?

发布时间:2020-12-14 02:02:44 所属栏目:Windows 来源:网络整理
导读:我想编写一个实用程序脚本,用于更改具有特定名称的文件夹图标.这在 python中可能吗?如果没有,还有其他方法吗? 谢谢 解决方法 import osimport ctypesfrom ctypes import POINTER,Structure,c_wchar,c_int,sizeof,byreffrom ctypes.wintypes import BYTE,WO
我想编写一个实用程序脚本,用于更改具有特定名称的文件夹图标.这在 python中可能吗?如果没有,还有其他方法吗?

谢谢

解决方法

import os
import ctypes
from ctypes import POINTER,Structure,c_wchar,c_int,sizeof,byref
from ctypes.wintypes import BYTE,WORD,DWORD,LPWSTR,LPSTR
import win32api    

HICON = c_int
LPTSTR = LPWSTR
TCHAR = c_wchar
MAX_PATH = 260
FCSM_ICONFILE = 0x00000010
FCS_FORCEWRITE = 0x00000002
SHGFI_ICONLOCATION = 0x000001000    

class GUID(Structure):
    _fields_ = [
        ('Data1',DWORD),('Data2',WORD),('Data3',('Data4',BYTE * 8)]

class SHFOLDERCUSTOMSETTINGS(Structure):
    _fields_ = [
        ('dwSize',('dwMask',('pvid',POINTER(GUID)),('pszWebViewTemplate',LPTSTR),('cchWebViewTemplate',('pszWebViewTemplateVersion',('pszInfoTip',('cchInfoTip',('pclsid',('dwFlags',('pszIconFile',('cchIconFile',('iIconIndex',c_int),('pszLogo',('cchLogo',DWORD)]

class SHFILEINFO(Structure):
    _fields_ = [
        ('hIcon',HICON),('iIcon',('dwAttributes',('szDisplayName',TCHAR * MAX_PATH),('szTypeName',TCHAR * 80)]    

def seticon(folderpath,iconpath,iconindex):
    """Set folder icon.

    >>> seticon(".","C:Windowssystem32SHELL32.dll",10)

    """
    shell32 = ctypes.windll.shell32

    folderpath = unicode(os.path.abspath(folderpath),'mbcs')
    iconpath = unicode(os.path.abspath(iconpath),'mbcs')

    fcs = SHFOLDERCUSTOMSETTINGS()
    fcs.dwSize = sizeof(fcs)
    fcs.dwMask = FCSM_ICONFILE
    fcs.pszIconFile = iconpath
    fcs.cchIconFile = 0
    fcs.iIconIndex = iconindex

    hr = shell32.SHGetSetFolderCustomSettings(byref(fcs),folderpath,FCS_FORCEWRITE)
    if hr:
        raise WindowsError(win32api.FormatMessage(hr))

    sfi = SHFILEINFO()
    hr = shell32.SHGetFileInfoW(folderpath,byref(sfi),sizeof(sfi),SHGFI_ICONLOCATION)
    if hr == 0:
        raise WindowsError(win32api.FormatMessage(hr))

    index = shell32.Shell_GetCachedImageIndexW(sfi.szDisplayName,sfi.iIcon,0)
    if index == -1:
        raise WindowsError()

    shell32.SHUpdateImageW(sfi.szDisplayName,index)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读