栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Windows中使用python安装字体

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Windows中使用python安装字体

这是

install_font
将字体复制到系统Fonts文件夹,在当前会话中加载它,通知正在运行的程序以及更新注册表的功能。它仅取决于Python的标准库,并且可以在Python
2和3中使用。

ctypes定义

import osimport shutilimport ctypesfrom ctypes import wintypestry:    import winregexcept importError:    import _winreg as winreguser32 = ctypes.WinDLL('user32', use_last_error=True)gdi32 = ctypes.WinDLL('gdi32', use_last_error=True)FONTS_REG_PATH = r'SoftwareMicrosoftWindows NTCurrentVersionFonts'HWND_BROADCAST   = 0xFFFFSMTO_ABORTIFHUNG = 0x0002WM_FonTCHANGE    = 0x001DGFRI_DEscriptION = 1GFRI_ISTRUETYPE  = 3if not hasattr(wintypes, 'LPDWORD'):    wintypes.LPDWORD = ctypes.POINTER(wintypes.DWORD)user32.SendMessageTimeoutW.restype = wintypes.LPVOIDuser32.SendMessageTimeoutW.argtypes = (    wintypes.HWND,   # hWnd    wintypes.UINT,   # Msg    wintypes.LPVOID, # wParam    wintypes.LPVOID, # lParam    wintypes.UINT,   # fuFlags    wintypes.UINT,   # uTimeout    wintypes.LPVOID) # lpdwResultgdi32.AddFontResourceW.argtypes = (    wintypes.LPCWSTR,) # lpszFilename# http://www.undocprint.org/winspool/getfontresourceinfogdi32.GetFontResourceInfoW.argtypes = (    wintypes.LPCWSTR, # lpszFilename    wintypes.LPDWORD, # cbBuffer    wintypes.LPVOID,  # lpBuffer    wintypes.DWORD)   # dwQueryType

功能定义

def install_font(src_path):    # copy the font to the Windows Fonts folder    dst_path = os.path.join(os.environ['SystemRoot'], 'Fonts',      os.path.basename(src_path))    shutil.copy(src_path, dst_path)    # load the font in the current session    if not gdi32.AddFontResourceW(dst_path):        os.remove(dst_path)        raise WindowsError('AddFontResource failed to load "%s"' % src_path)    # notify running programs    user32.SendMessageTimeoutW(HWND_BROADCAST, WM_FONTCHANGE, 0, 0,         SMTO_ABORTIFHUNG, 1000, None)    # store the fontname/filename in the registry    filename = os.path.basename(dst_path)    fontname = os.path.splitext(filename)[0]    # try to get the font's real name    cb = wintypes.DWORd()    if gdi32.GetFontResourceInfoW(filename, ctypes.byref(cb), None, GFRI_DEscriptION):        buf = (ctypes.c_wchar * cb.value)()        if gdi32.GetFontResourceInfoW(filename, ctypes.byref(cb), buf,     GFRI_DEscriptION): fontname = buf.value    is_truetype = wintypes.BOOL()    cb.value = ctypes.sizeof(is_truetype)    gdi32.GetFontResourceInfoW(filename, ctypes.byref(cb),        ctypes.byref(is_truetype), GFRI_ISTRUETYPE)    if is_truetype:        fontname += ' (TrueType)'    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, FONTS_REG_PATH, 0,  winreg.KEY_SET_VALUE) as key:        winreg.SetValueEx(key, fontname, 0, winreg.REG_SZ, filename)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/668044.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号