如何获取字体文件图标?

时间:2012-11-15 08:12:34

标签: delphi winapi icons

我可以像这样获得字体文件夹图标:

var
sfi : SHFILEINFO;
begin
  SHGetFileInfo('C:\Windows\Fonts\Arial' , 0 , sfi , SizeOf(sfi) , SHGFI_ICON);
  Image1.Picture.Icon.Handle := sfi.hIcon;
end;

但是这样失败了:

var
sfi : SHFILEINFO;
begin
  SHGetFileInfo('C:\Windows\Fonts\ARIALN.TTF' , 0 , sfi , SizeOf(sfi) , SHGFI_ICON);  
  Image1.Picture.Icon.Handle := sfi.hIcon;
end;
看起来好像无法获取字体文件的图标但可以获取字体文件夹,我想知道如何获取字体文件图标?

2 个答案:

答案 0 :(得分:1)

我的猜测是你想要一个与文件类型相关联的图标(例如TTF)。然后你可以问这个问题。例如,

var
  sfi: SHFILEINFO;
begin
  SHGetFileInfo('C:\SomeFileThatNeedNotEvenExist.ttf',
    0, sfi, SizeOf(sfi), SHGFI_USEFILEATTRIBUTES or SHGFI_ICON);
  Image1.Picture.Icon.Handle := sfi.hIcon;

将为您提供与TTF文件相关联的图标。

答案 1 :(得分:0)

使用Windows Shell获取字体文件图标:

代码:

var
  psfDeskTop : IShellFolder;
  psfFont : IShellFolder;
  pEnumList : IEnumIdList;
  pidFont : PItemIdList;
  pidChild : PItemIdList;
  FontPath : array[0..MAX_PATH - 1] of Char;
  IconFile : array[0..MAX_PATH - 1] of Char;
  pchEaten, dwAttributes, ItemsFetched : ULONG;
  ExtractIcon : IExtractIcon;
  IconIndex : Integer;
  Flags : DWORD;
  Icon : TIcon;
  LH, SH : HICon;
begin
  FillChar(FontPath, sizeof(FontPath), #0);
  //get C:\Windows\Fonts
  SHGetSpecialFolderPath(0, FontPath, CSIDL_FONTS, False);
  SHGetDesktopFolder(psfDeskTop);
  psfDeskTop.ParseDisplayName(0, nil, FontPath, pchEaten, pidFont,
    dwAttributes);
  //get font folder's interface
  psfDeskTop.BindToObject(pidFont, nil, IID_IShellFolder, psfFont);
  //Enumerate
  psfFont.EnumObjects(0, SHCONTF_FOLDERS or SHCONTF_NONFOLDERS or
    SHCONTF_INCLUDEHIDDEN, pEnumList);
  ItemsFetched := 0;

  while pEnumList.Next(1, pidChild, ItemsFetched) = NO_ERROR do
  begin

    psfFont.GetUIObjectOf(0, 1, pidChild, IID_IExtractIconW, nil,
      Pointer(ExtractIcon));

    Flags := 0;
    LH := 0;
    SH := 0;

    if Assigned(ExtractIcon) then
    begin
      IconIndex := 0;
      Icon := TIcon.Create;
      ExtractIcon.GetIconLocation(0, @IconFile, MAX_PATH, IconIndex,
        Flags);
      if (IconIndex < 0) or ((Flags and GIL_NOTFILENAME) = 0) then
        ExtractIconEx(@IconFile, IconIndex, LH, SH, 1)
      else
        ExtractIcon.Extract(@IconFile, IconIndex, LH, SH, MakeLong(32,
          16));

      //get font file icon's handle LS for large icon , SH for small icon
      //do something u want 

    end;

  end;

end;