枚举安装的字体
InstalledFontCollection 类继承自 FontCollection 抽象基类。 可以使用 InstalledFontCollection 对象枚举计算机上安装的字体。 InstalledFontCollection 对象的 FontCollection::GetFamilies 方法返回 FontFamily 对象的数组。 在调用 FontCollection::GetFamilies 之前,必须分配一个足够大的缓冲区来容纳该数组。 若要确定所需缓冲区的大小,请调用 FontCollection::GetFamilyCount 方法,并将返回值乘以 (FontFamily) 的大小。
以下示例列出了安装在计算机上的所有字体系列的名称。 该代码通过调用 FontCollection::GetFamilies 返回的数组中每个 FontFamily 对象的 FontFamily::GetFamilyName 方法来检索字体系列名称。 检索系列名称时,它们会串联成以逗号分的列表。 然后,Graphics 类的 DrawString 方法在矩形中绘制逗号分隔的列表。
FontFamily fontFamily(L"Arial");
Font font(&fontFamily, 8, FontStyleRegular, UnitPoint);
RectF rectF(10.0f, 10.0f, 500.0f, 500.0f);
SolidBrush solidBrush(Color(255, 0, 0, 0));
INT count = 0;
INT found = 0;
WCHAR familyName[LF_FACESIZE]; // enough space for one family name
WCHAR* familyList = NULL;
FontFamily* pFontFamily = NULL;
InstalledFontCollection installedFontCollection;
// How many font families are installed?
count = installedFontCollection.GetFamilyCount();
// Allocate a buffer to hold the array of FontFamily
// objects returned by GetFamilies.
pFontFamily = new FontFamily[count];
// Get the array of FontFamily objects.
installedFontCollection.GetFamilies(count, pFontFamily, &found);
// The loop below creates a large string that is a comma-separated
// list of all font family names.
// Allocate a buffer large enough to hold that string.
familyList = new WCHAR[count*(sizeof(familyName)+ 3)];
StringCchCopy(familyList, 1, L"");
for(INT j = 0; j < count; ++j)
{
pFontFamily[j].GetFamilyName(familyName);
StringCchCatW(familyList, count*(sizeof(familyName)+ 3), familyName);
StringCchCatW(familyList, count*(sizeof(familyName)+ 3), L", ");
}
// Draw the large string (list of all families) in a rectangle.
graphics.DrawString(
familyList, -1, &font, rectF, NULL, &solidBrush);
delete [] pFontFamily;
delete [] familyList;
下图显示了上述代码的可能输出。 如果运行代码,输出可能会有所不同,具体取决于计算机上安装的字体。