【发布时间】:2014-03-19 12:21:33
【问题描述】:
以下是我处理表单中所有可用文本框的 gotfocus 和 lostfocus 事件的代码。
private void Form1_Load(object sender, EventArgs e)
{
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
c.GotFocus += new System.EventHandler(this.txtGotFocus);
c.LostFocus += new System.EventHandler(this.txtLostfocus);
}
}
}
private void txtGotFocus(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
if (tb != null)
{
tb.BackColor = Color.Silver;
tb.BorderStyle = BorderStyle.FixedSingle;
}
}
private void txtLostFocus(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
if (tb != null)
{
tb.BackColor = Color.White;
tb.BorderStyle = BorderStyle.Fixed3D;
}
}
它适用于第一个文本框,但是当我通过按 Tab 键转到下一个文本框时,它会重复调用这两个事件,并且文本框的行为就像闪烁一样。一段时间后,错误消息显示在代码中,例如:
对“System.Windows.Forms!System.Windows.Forms.NativeMethods+WndProc::Invoke”类型的垃圾收集委托进行了回调。这可能会导致应用程序崩溃、损坏和数据丢失。将委托传递给非托管代码时,托管应用程序必须使它们保持活动状态,直到保证它们永远不会被调用。
代码有什么问题?有什么解决办法吗?
【问题讨论】: