在Windows中使用python安装字体

在Windows中使用python安装字体,第1张

在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)


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5673301.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存