我有带有自定义字体和计时器的标签,它们会更改标签中的值。我的应用程序开始最小化。当我显示应用程序时,有时会显示异常,并且标签中的文本不是红十字。
在这里我尝试调用异步方法来更改标签文本
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 更改的方法
private void showTime()
{
label1.Text = time.ToString();
}
*****
问题是PrivateFontCollection
实例中的pfc
变量超出范围,并且有时在第一次绘制控件之前收集(这似乎之后获得了对实例的强引用)。
将实例移到方法之外以防止 GC 收集它:
class Form1 : Form
{
readonly PrivateFontCollection _pfc = new PrivateFontCollection();
public Form1()
{
...
_pfc.AddFontFile(appPath + @"/font.ttf");
...
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)