3

When I click enter-button, MessageBox is shown. I want MessageBox to close when I click enter-button again as usual. Problem is - it doesn't have focus, but TextBox has and when I click enter-button _textBox_OnKeyUp eventhandler is invoked again and again. How can I solve my problem?

Markup:

<Grid>
    <TextBox Name="_textBox"
        Width="100"
        Height="30"
        Background="OrangeRed"
        KeyUp="_textBox_OnKeyUp"/>
</Grid>

Code:

private void _textBox_OnKeyUp(object sender, KeyEventArgs e)
{
    if (e.Key != Key.Enter)
        return;

    MessageBox.Show("Bla-bla");
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
monstr
  • 1,680
  • 1
  • 25
  • 44
  • show this, I think, it is same with your case: http://stackoverflow.com/questions/6882196/wpf-command-for-textbox-which-fires-up-when-we-hit-enter-key-on-it – Mouaici_Med Apr 06 '16 at 07:41
  • It is one of the infamous airspace issues, activation and focus needs to be emulated in WPF because controls are not windows. That can be quite glitchy if you don't do it the "normal" way, WPF has a hard-baked assumption that shortcut keystrokes are implemented with the KeyDown notification. Using that event instead trivially solves your problem. – Hans Passant Apr 06 '16 at 09:02

2 Answers2

3

You could use KeyDown event instead because the MessageBox responds to the KeyDown event:

<TextBox Name="_textBox"
         Width="100"
         Height="30"
         Background="OrangeRed"
         KeyDown="_textBox_OnKeyDown"/>

And:

private void _textBox_OnKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key != Key.Enter)
       return;

    MessageBox.Show("Bla-bla");
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
1

I recomend using this method of Messagebox.

MessageBox.Show(Window, String)

Taken from the MSDN :

Displays a message box in front of the specified window. The message box displays a message and returns a result.

You can use this as the following :

MessageBox.Show(Application.Current.MainWindow, "I'm on top of teh window so I should get focus");

EDIT :

You should give back the focus to your main window before calling the MessageBox.

private void _textBox_OnKeyUp(object sender, KeyEventArgs e)
{
    if (e.Key != Key.Enter)
        return;

    //this.Focus() or at least YourWindow.Focus()
    MessageBox.Show("Bla-bla");
}