Search code examples
c#wpffocusmessageboxkeyup

MessageBox doesn't take focus


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

Solution

  • 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");
    }