2014-09-05 34 views
0

我的問題是:在C#中fflush()從C中有類似的東西嗎?

用戶可以搜索地址。如果找不到任何東西,用戶會看到一個消息框。他可以按ENTER鍵關閉它。到現在爲止還挺好。調用SearchAddresses()也可以通過點擊ENTER來啓動。而現在用戶處於無限循環,因爲每個ENTER(讓消息框消失)開始一個新的搜索。

這裏的隱藏代碼:

private void TxtBoxAddress_KeyUp(object sender, KeyEventArgs e) 
    { 
     if (e.Key == Key.Enter) 
      btnSearch_Click(sender, e); 
    } 


private void queryTask_Failed(object sender, TaskFailedEventArgs e) 
    { 
     //throw new NotImplementedException(); 
     MessageBox.Show("*", "*", MessageBoxButton.OK); 
     isMapNearZoomed = false; 
    } 

而且這裏的XAML代碼:

<TextBox Background="Transparent" Name="TxtBoxAddress" Width="200" Text="" KeyUp="TxtBoxAddress_KeyUp"></TextBox> 

<Button Content="Suchen" Name="btnSearch" Click="btnSearch_Click" Width="100"></Button> 

我該如何處理在C#這個死循環?

+3

不知道這有下與fflush做什麼呢? – AnthonyLambert 2014-09-05 12:46:36

+0

我認爲你的問題不夠清楚。請考慮重述並記住,我們不知道這個問題。此外,似乎代碼的某些部分也丟失了。 – Krumia 2014-09-05 12:47:06

+4

爲什麼不將BtnSearch設置爲默認按鈕,以便在文本框Key Up事件中沒有邏輯? – 2014-09-05 12:47:08

回答

2

大聲笑。這是一個有趣的無限循環。 Theres很多答案。

嘗試添加全局字符串_lastValueSearched。

private string _lastValueSearched; 

private void TxtBoxAddress_KeyUp(object sender, KeyEventArgs e) 
    { 
    if (e.Key == Key.Enter && _lastValueSearched != TxtBoxAddress.Text) 
     { 
     //TxtBoxAddress.LoseFocus(); 
     btnSearch_Click(sender, e); 
     _lastValueSearched = TxtBoxAddress.Text; 
     } 
    } 


private void queryTask_Failed(object sender, TaskFailedEventArgs e) 
{ 
    //throw new NotImplementedException(); 
    MessageBox.Show("*", "*", MessageBoxButton.OK); 
    isMapNearZoomed = false; 
} 

因此,在第一次輸入內部TxtBoxAddress,lastSearchValue成爲新的搜索值。當他們在消息框上按Enter時,如果TxtBoxAddress文本沒有改變,那麼if語句將不會被觸發。

另外,該行註釋掉了,TxtBoxAddres.LoseFocus()可以獨立工作。這應該將焦點從TextBox中移除,因此當用戶按下消息框上的Enter時,TextBox KeyDown不應該觸發。

0

使用KeyPress事件,而不是KeyUp

private void textBox_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (e.KeyChar == 13) // handle 'Enter' key 
     MessageBox.Show("test"); 
} 
+2

是的。只是想補充一點:問題在於msgbox在keydown上關閉,並且當焦點變回到文本框時鍵仍然按下,當釋放鍵時,文本框會接收到鍵入事件。但使用默認按鈕將是一個更清潔的解決方案。 – ths 2014-09-05 13:02:19

相關問題