如何在Delphi中检测等宽字体?

Tah*_*htu 5 delphi winapi delphi-xe4

如何在Delphi中检测等宽字体?

TFont.Pitch应该是fpFixed我认为,但它对Delphi XE4不起作用:

var
  Font: TFont;
begin
  Font := TFont.Create;
  Font.Name := 'Courier New';
  if Font.Pitch = fpFixed then
    ShowMessage('Monospace Font!');
  ...
Run Code Online (Sandbox Code Playgroud)

Font.Pitch基于GetObjectWinAPI.它应该返回lfPitchAndFamily FIXED_PITCH,但我总是得到DEFAULT_PITCH所有字体(也适用于Arial).

MBo*_*MBo 5

是的,GetObject真的回归DEFAULT_PITCH.但是你可以通过枚举具有所需名称的字体来获得真正的价值:

function EnumFontsProc(var elf: TEnumLogFont;
                       var tm: TNewTextMetric;
                       FontType: Integer;
                       Data: LPARAM): Integer; stdcall;
begin;
  Result := Integer(FIXED_PITCH = (elf.elfLogFont.lfPitchAndFamily and FIXED_PITCH));
end;

procedure TForm1.Button13Click(Sender: TObject);
begin;
  if EnumFontFamilies(Canvas.Handle,
                      PChar('Courier New'),
                      @EnumFontsProc,0) then
     Caption := 'Fixed'
  else
     Caption := 'Variable';
end;
Run Code Online (Sandbox Code Playgroud)