locked
Infinite loop when pushing enter in a message box RRS feed

  • Question

  • This must be a really simple problem but can't get rid of it. I've made up a sample program and I'll explain my problem afterwards.

    <Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1">
        <StackPanel>
            <TextBox x:Name="TextBox" Width="200" KeyUp="TextBox_KeyUp" />
        </StackPanel>
    </Window>


    And the code behind:

    public partial class Window1 : Window
        {
            public Window1()
            {
                InitializeComponent();
            }
    
            private void TextBox_KeyUp(object sender, KeyEventArgs e)
            {
                if (e.Key == Key.Enter && TextBox.Text == "hello world")
                {
                    MessageBox.Show("Correct word!", "Success", MessageBoxButton.OK);
                }
            }
        }



    The problem appears if you type in "hello world" in the text box, push enter and then push enter again when the message box is vissible. Right now the messeage box keeps pop up as long as you push enter when the message box is vissible. As you might understand I want to return to the text box if I push enter when the message box is vissible, not get a new message box.

    Hope anyone have I bright solution for this :)

    Regards,
    Fredrik
    Tuesday, March 31, 2009 3:03 PM

Answers

  • You should modify your code so that you only process the enter KeyUp if you previously received a KeyDown for it. You'll always get a KeyUp after dismissing a dialog because it's the KeyDown that dismisses the dialog.
    Controls for WPF, Windows Forms and Silverlight at http://www.divelements.co.uk
    • Proposed as answer by joeAtBluebeam Tuesday, March 31, 2009 11:12 PM
    • Marked as answer by Tao Liang Tuesday, April 7, 2009 1:50 AM
    Tuesday, March 31, 2009 3:20 PM