2016-07-04 85 views
-2

我有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

我缺少什麼?

+2

了'System.Threading.Timer'運行在後臺線程上。要訪問您必須調用的UI元素,或者使用「System.Windows.Forms.Timer」。 - 另外,在問題中包含實際的錯誤消息_是一個好習慣。一個異常可以有任何錯誤信息,所以只告訴異常類型會使得看到實際問題變得更加困難。 –

回答

2

System.Threading.Timer在後臺線程,這意味着爲了訪問UI元素必須執行調用或使用System.Windows.Forms.Timer代替運行。

我推薦System.Windows.Forms.Timer解決方案,因爲這是最簡單的。無需部署和重新初始化定時器,只是在形式的構造函數初始化和使用Start()Stop()方法:

System.Windows.Forms.Timer textTimer; 

public Form1() //The form constructor. 
{ 
    InitializeComponent(); 
    textTimer = new System.Windows.Forms.Timer(); 
    textTimer.Interval = 300; 
    textTimer.Tick += new EventHandler(textTimer_Tick); 
} 

private void textTimer_Tick(Object sender, EventArgs e) 
{ 
    if (textSearchString.Focused) { 
     populateGrid(); 
     textTimer.Stop(); //No disposing required, just stop the timer. 
    } 
} 

private void textSearchString_TextChanged(object sender, EventArgs e) 
{ 
    textTimer.Start(); 
} 
+0

重寫OnLoad方法將避免「訂閱正確的事件」問題,或者只使用表單的構造函數。 – LarsTech

+0

@LarsTech:True ...更新。 –

0

試試這個..

private async void textSearchString_TextChanged(object sender, EventArgs e) 
{ 
    await Task.Delay(300); 
    //more code 
}