2016-07-04 1 views
-2

TextChanged 이벤트를 사용하여 텍스트 상자의 키 입력에 반응하는 WinForms 응용 프로그램이 있습니다. 마지막 키 입력 이후 짧은 간격 (어쩌면 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.FocusedSystem.InvalidOperationException을 발생한다는 것입니다.

무엇이 누락 되었습니까?

+2

를 A는'System.Threading.Timer' 실행 배경 스레드. UI 요소에 액세스하려면 호출해야하며 그렇지 않으면'System.Windows.Forms.Timer'를 대신 사용하십시오. 또한 질문에 실제 오류 메시지 _ 포함하는 것이 좋습니다. 예외에는 모든 오류 메시지가있을 수 있으므로 예외 유형 만 알려주면 실제 문제를 보는 것이 훨씬 어려워집니다. –

답변

2

UI 요소를 액세스하기 위해 당신이 호출을 수행하거나 대신 System.Windows.Forms.Timer를 사용해야 함을 의미합니다 배경 스레드에 System.Threading.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 
} 
관련 문제