我有WinForms應用程序,使用TextChanged
事件對文本框中的按鍵作出反應。我想延遲反應,直到自最後一次擊鍵後出現短距離(也許是300毫秒)。下面是我當前的代碼:延遲反應TextChanged事件
private void TimerElapsed(Object obj)
{
if (textSearchString.Focused)
{ //this code throws exception
populateGrid();
textTimer.Dispose();
textTimer = null;
}
}
private void textSearchString_TextChanged(object sender, EventArgs e)
{
if (textTimer != null)
{
textTimer.Dispose();
textTimer = null;
}
textTimer = new System.Threading.Timer(TimerElapsed, null, 1000, 1000);
}
我的問題是textSearchString.Focused
拋出一個System.InvalidOperationException
。
我缺少什麼?
了'System.Threading.Timer'運行在後臺線程上。要訪問您必須調用的UI元素,或者使用「System.Windows.Forms.Timer」。 - 另外,在問題中包含實際的錯誤消息_是一個好習慣。一個異常可以有任何錯誤信息,所以只告訴異常類型會使得看到實際問題變得更加困難。 –