如何:枚举已安装的字体

更新:2007 年 11 月

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

示例

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

如果运行该示例代码,输出将与下面的插图所显示的情况相似。

已安装的字体

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)

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);

编译代码

前面的示例是为使用 Windows 窗体而设计的,它需要 PaintEventHandler 的参数 PaintEventArgse。

请参见

其他资源

使用字体和文本