简体   繁体   中英

Is there something similar in C# to fflush() from C?

My problem is:

The user can search an address. If there was nothing found, the user sees an messagebox. He can close it by pressing ENTER. So far, so good. Calling SearchAddresses() can also be started by hitting ENTER. And now the user is in an endless loop because every ENTER (to let the messagebox disappear) starts an new search.

Here the codebehind:

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;
    }

And here the xaml code:

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

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

How can I handle this endless loop in C#?

Lol. Thats a funny infinate loop. Theres lots of answers.

Try adding a global string, _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;
 }

So on the first enter insider the TxtBoxAddress, the lastSearchValue becomes the new search value. When they press enter on the messagebox, if the TxtBoxAddress text hasn't changed, the if statement will not trigger.

Alternativly, the line commented out, TxtBoxAddres.LoseFocus() may work by itself. This should take the focus off of the TextBox, so when the user presses enter on the messagebox, the TextBox KeyDown shouldn't fire.

Use KeyPress event instead of KeyUp :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM