列舉已安裝的字型
InstalledFontCollection類別繼承自FontCollection抽象基類。 您可以使用 InstalledFontCollection 物件來列舉電腦上安裝的字型。 InstalledFontCollection物件的FontCollection::GetFamilies方法會傳回FontFamily物件的陣列。 呼叫 FontCollection::GetFamilies之前,您必須配置足以保存該陣列的緩衝區。 若要判斷必要緩衝區的大小,請呼叫 FontCollection::GetFamilyCount 方法,並將傳回值乘以 sizeof (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;
下圖顯示上述程式碼的可能輸出。 如果您執行程式碼,輸出可能會有所不同,視電腦上安裝的字型而定。