Share via


インストールされているフォントの列挙

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;
            

次の図は、上記のコードの可能な出力を示しています。 コードを実行すると、コンピューターにインストールされているフォントに応じて出力が異なる場合があります。

インストールされているフォント ファミリのコンマ区切りの一覧を含むウィンドウのスクリーン ショット