delphifonts

How to detect if a specific font style is installed?


How do I detect if a specific style of a font family is installed within the family?

In some VCL projects, I have a UI that uses Roboto Bold. If the user has Roboto installed, but not the specific Roboto Bold style font, the system will substitute Roboto and "bold" it, which results in a slightly wider spacing which sometimes results in an unexpected line wrap.

I can easily detect if Roboto is installed with Screen.Fonts.IndexOf('Roboto'), but that returns true even if Roboto Bold is not installed. And Roboto Bold does not show up in Screen.Fonts, since that list only shows family names.

How can I drill down within the family to see which actual fonts are installed?


Solution

  • working from Stijn's answer, I edited a bit to make it work for me. Font is installed if IsFontInstalled returns 0

    function CheckFontCB(const lf:TLogFont;const tm:TTextMetric;ft:DWORD;lParam:NativeInt):integer; stdcall;
    begin
      Result:=0;//found one! EnumFontFamiliesEx can stop enumerating now, and will return 0
    end;
    
    function IsFontInstalled(const x:string):integer;
    var
      i,l:integer;
      lf:TLogFont;
    begin
      ZeroMemory(@lf,SizeOf(TLogFont));
      lf.lfCharSet:=DEFAULT_CHARSET;
      l:=Length(x);
      if l>=LF_FACESIZE then raise Exception.Create('Invalid font name length');
      for i:=0 to l-1 do lf.lfFaceName[i]:=x[i+1];
      lf.lfFaceName[l]:=#0;
      Result:=EnumFontFamiliesEx(GetDC(0),lf,@CheckFontCB,0,0);
    end;
    

    Thanks!

    Scott