如何:列舉已安裝的字型
InstalledFontCollection 類別繼承自抽象基底類別 FontCollection。 您可以使用 InstalledFontCollection 物件來列舉電腦上安裝的字型。 InstalledFontCollection 物件的 Families 屬性是 FontFamily 物件的陣列。
範例
下列範例會列出電腦上所安裝所有字型系列的名稱。 程式碼會擷取 Families 屬性所傳回陣列中每個 FontFamily 物件的 Name 屬性。 擷取姓氏時,會串連成以逗號分隔的清單。 然後,Graphics 類別的 DrawString 方法會在矩形中繪製逗號分隔清單。
如果您執行範例程式碼,輸出會類似於下圖所示:
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 Forms 搭配使用,而且需要 PaintEventArgse
,這是 PaintEventHandler 的參數。 此外,您應該匯入 System.Drawing.Text 命名空間。