如何:枚举已安装的字体

InstalledFontCollection 类继承自 FontCollection 抽象基类。 可以使用 InstalledFontCollection 对象来枚举计算机上安装的字体。 InstalledFontCollection 对象的 Families 属性是一个包含 FontFamily 对象的数组。

示例

以下示例列出了安装在计算机上的所有字体系列的名称。 该代码检索由 Families 属性返回的数组中每个 FontFamily 对象的 Name 属性。 检索系列名称时,它们会串联成以逗号分的列表。 然后,Graphics 类的 DrawString 方法会在矩形中绘制逗号分隔的列表。

如果运行示例代码,输出将类似于下图所示:

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 窗体,需要 PaintEventArgse,这是 PaintEventHandler 的参数。 此外,应导入 System.Drawing.Text 命名空间。

另请参阅