【发布时间】:2012-01-28 11:07:24
【问题描述】:
由于内置字体对话框在选择非 True Type 字体时返回“Not a True Type Font”异常,我正在尝试使用过滤掉非 True Type 字体的字体系列创建自定义字体对话框。
控件运行良好,但我需要此对话框的大小和样式选择器。我正在发布当前代码。请帮我添加尺寸和样式选择器。它也可能对您有用。
public class FontListBox : ListBox
{
private List<Font> _fonts = new List<Font>();
private Brush _foreBrush;
public FontListBox()
{
DrawMode = DrawMode.OwnerDrawFixed;
ItemHeight = 20;
foreach (FontFamily ff in FontFamily.Families)
{
// determine the first available style, as all fonts don't support all styles
FontStyle? availableStyle = null;
foreach (FontStyle style in Enum.GetValues(typeof(FontStyle)))
{
if (ff.IsStyleAvailable(style))
{
availableStyle = style;
break;
}
}
if (availableStyle.HasValue)
{
Font font = null;
try
{
// do your own Font initialization here
// discard the one you don't like :-)
font = new Font(ff, 12, availableStyle.Value);
}
catch
{
}
if (font != null)
{
_fonts.Add(font);
Items.Add(font);
}
}
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (_fonts != null)
{
foreach (Font font in _fonts)
{
font.Dispose();
}
_fonts = null;
}
if (_foreBrush != null)
{
_foreBrush.Dispose();
_foreBrush = null;
}
}
public override Color ForeColor
{
get
{
return base.ForeColor;
}
set
{
base.ForeColor = value;
if (_foreBrush != null)
{
_foreBrush.Dispose();
}
_foreBrush = null;
}
}
private Brush ForeBrush
{
get
{
if (_foreBrush == null)
{
_foreBrush = new SolidBrush(ForeColor);
}
return _foreBrush;
}
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
base.OnDrawItem(e);
if (e.Index < 0)
return;
e.DrawBackground();
e.DrawFocusRectangle();
Rectangle bounds = e.Bounds;
Font font = (Font)Items[e.Index];
e.Graphics.DrawString(font.Name, font, ForeBrush, bounds.Left, bounds.Top);
}
}
public partial class MyFontDialog : Form
{
private FontListBox _fontListBox;
public MyFontDialog()
{
InitializeComponent();
_fontListBox = new FontListBox();
_fontListBox.Dock = DockStyle.Fill;
Controls.Add(_fontListBox);
}
}
我在 sourceforge https://sourceforge.net/p/newfontpicker/ 主持了这个项目
【问题讨论】:
-
FontDialog 类已经过滤了非 TrueType 字体。这里真正的解决方案是卸载具有错误元数据的字体。
-
它试图过滤掉这些opentype字体,但有些字体仍然存在。见connect.microsoft.com/VisualStudio/feedback/details/708872/…
标签: c# .net winforms fonts dialog