我有自定义字体和计时器的标签,可以更改标签中的值。我的应用程序开始最小化。当我显示应用程序时,有时会显示异常并且标签中的文本是红色的。
这里我尝试调用标签文本更改的异步方法
private void timer1_Tick(object sender, EventArgs e)
{
// create a delegate of MethodInvoker poiting to showTime function.
MethodInvoker simpleDelegate = new MethodInvoker(showTime);
// Calling showTime Async
simpleDelegate.BeginInvoke(null, null);
}
字体加载
public Form1()
{
InitializeComponent();
SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); //event handler for windows lock
File.WriteAllBytes(appPath + "\\font.ttf", Resources.font); //copy font from resources
try
{
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile(appPath + @"/font.ttf");
label1.Font = new Font(pfc.Families[0], 11, FontStyle.Bold);
}
catch
{
MessageBox.Show("Failed to load nice font." + "\r\n" + "Using standart font instead.", "Time app", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
这里是标签tet change的方法
private void showTime()
{
label1.Text = time.ToString();
}
** * ** 异常文字 的 ** * ****
System.ArgumentException: Parameter is not valid.
at System.Drawing.FontFamily.GetName(Int32 language)
at System.Drawing.FontFamily.get_Name()
at System.Windows.Forms.Internal.WindowsFont.FromFont(Font font, WindowsFontQuality fontQuality)
at System.Windows.Forms.Internal.WindowsGraphicsCacheManager.GetWindowsFont(Font font, WindowsFontQuality fontQuality)
at System.Windows.Forms.TextRenderer.MeasureText(String text, Font font, Size proposedSize, TextFormatFlags flags)
at System.Windows.Forms.Layout.LayoutUtils.MeasureTextCache.GetUnconstrainedSize(String text, Font font, TextFormatFlags flags)
at System.Windows.Forms.Layout.LayoutUtils.MeasureTextCache.TextRequiresWordBreak(String text, Font font, Size size, TextFormatFlags flags)
at System.Windows.Forms.Label.CreateTextFormatFlags(Size constrainingSize)
at System.Windows.Forms.Label.CreateTextFormatFlags()
at System.Windows.Forms.Label.OnPaint(PaintEventArgs e)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Label.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
问题:当我使用自定义字体时如何摆脱这个异常?
答案 0 :(得分:4)
问题是PrivateFontCollection
变量中的pfc
实例超出了范围,并且在第一次绘制控件之前有时被收集了之后获得对实例的强烈引用。)
将实例移到方法之外以防止GC收集它:
class Form1 : Form
{
readonly PrivateFontCollection _pfc = new PrivateFontCollection();
public Form1()
{
...
_pfc.AddFontFile(appPath + @"/font.ttf");
...
}
}
答案 1 :(得分:-1)
以下是此处另一个问题中使用的示例。它显示了您的需求。 http://www.bobpowell.net/embedfonts.htm