如何:列舉已安裝的字型

類別 InstalledFontCollection 繼承自 FontCollection 抽象基類。 您可以使用 InstalledFontCollection 物件來列舉電腦上安裝的字型。 物件的 Families 屬性 InstalledFontCollection 是 物件的陣列 FontFamily

範例

下列範例會列出電腦上安裝之所有字型系列的名稱。 程式碼會 Name 擷取 屬性所 Families 傳回陣列中每個 FontFamily 物件的 屬性。 擷取姓氏時,會串連成以逗號分隔的清單。 然後,類別 DrawStringGraphics 方法會在矩形中繪製逗號分隔清單。

如果您執行範例程式碼,輸出會類似下圖所示:

Screenshot that shows the installed font families.

FontFamily fontFamily = new FontFamily("Arial");
Font font = new Font(
   fontFamily,
   8,
   FontStyle.Regular,
   GraphicsUnit.Point);
RectangleF rectF = new RectangleF(10, 10, 500, 500);
SolidBrush solidBrush = new SolidBrush(Color.Black);

string familyName;
string familyList = "";
FontFamily[] fontFamilies;

InstalledFontCollection installedFontCollection = new InstalledFontCollection();

// Get the array of FontFamily objects.
fontFamilies = installedFontCollection.Families;

// The loop below creates a large string that is a comma-separated
// list of all font family names.

int count = fontFamilies.Length;
for (int j = 0; j < count; ++j)
{
    familyName = fontFamilies[j].Name;
    familyList = familyList + familyName;
    familyList = familyList + ",  ";
}

// Draw the large string (list of all families) in a rectangle.
e.Graphics.DrawString(familyList, font, solidBrush, rectF);
Dim fontFamily As New FontFamily("Arial")
Dim font As New Font( _
   fontFamily, _
   8, _
   FontStyle.Regular, _
   GraphicsUnit.Point)
Dim rectF As New RectangleF(10, 10, 500, 500)
Dim solidBrush As New SolidBrush(Color.Black)

Dim familyName As String
Dim familyList As String = ""
Dim fontFamilies() As FontFamily

Dim installedFontCollection As New InstalledFontCollection()

' Get the array of FontFamily objects.
fontFamilies = installedFontCollection.Families

' The loop below creates a large string that is a comma-separated
' list of all font family names.
Dim count As Integer = fontFamilies.Length
Dim j As Integer

While j < count
    familyName = fontFamilies(j).Name
    familyList = familyList & familyName
    familyList = familyList & ",  "
    j += 1
End While

' Draw the large string (list of all families) in a rectangle.
e.Graphics.DrawString(familyList, font, solidBrush, rectF)

編譯程式碼

上述範例設計是為搭配 Windows Form 使用所設計,而且需要 PaintEventArgse,這是 PaintEventHandler 的參數。 此外,您應該匯入 System.Drawing.Text 命名空間。

另請參閱