5

I want to install new fonts on windows with Python 2.7. First I copied myFont.ttf to windows Fonts folder then I Added My Font (True Type) key to registry (HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts). Now I want to declare system that a new font has been installed. For this I found that I should use win32api.SendMessage, But I don't know how to provide required arguments for this method?

Is there anyway to install ttf fonts on windows with python? I googled it but I couldn't find useful data on Python.

1 Answers1

6
import win32api
import win32con
import ctypes

ctypes.windll.gdi32.AddFontResourceA("C:\\Users\\Username\\Desktop\\fontname.ttf")
win32api.SendMessage(win32con.HWND_BROADCAST, win32con.WM_FONTCHANGE)
  • 2
    Avoid `ctypes.windll` (it's a bad idea to use globally cached function pointer objects); avoid legacy [A]NSI APIs (Windows filesystem paths are natively UTF-16; don't put yourself in an 8-bit codepage box from the 1980s); and check return values: `gdi32 = ctypes.WinDLL('gdi32');` `result = gdi32.AddFontResourceW(u"C:\\Users\\Username\\Desktop\\fontname.ttf")`. – Eryk Sun Jan 24 '17 at 19:02
  • @ErykSun does the `WinDLL` package automatically convert Unicode strings to UTF-16? You can't count on the internal representations of strings in the latest versions of Python. – Mark Ransom May 25 '20 at 19:46
  • @MarkRansom, it's a function of ctypes argument parsing, not the `ctypes.WinDLL` subclass of `ctypes.CDLL`. If the function pointer's `argtypes` attribute isn't set, then Unicode arguments are passed as `wchar_t *` strings, whatever has to be done to obtain that. In 3.x, ctypes calls `PyUnicode_AsWideCharString` and keeps a reference to the memory in a capsule object until the call returns (i.e. don't rely on this automatic conversion if the library will retain a reference to the string). In Windows, the wide-character string will be UTF-16, with surrogate pairs for non-BMP codes. – Eryk Sun May 25 '20 at 20:28
  • it just doesn't work. code executed but nothing added to my fonts – greendino Oct 14 '20 at 07:15