简体   繁体   中英

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

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

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

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