Detecting when you press "Enter" in a WPF TextBox

Hey all,

You have a TextBox and you want to detect when someone presses “Enter” and do something different than if they type text.

This one is simple, but you need to be careful when closing a window in multiple places.

The Event you want to use is KeyDown.

Imagine you have a TextBox called TextBoxCompanyName where you are asking the company name.  It is common to enter the name and press Enter and have “Enter” act just like the OK button.

You already have an OK button and it is setup to close the window or do other stuff first.


        private void ButtonOK_Click(object sender, RoutedEventArgs e)
        {
            // May do other stuff.
            this.Close();
        }

        private void TextBoxCompanyName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                ButtonOK_Click(this, new RoutedEventArgs());
            }
        }

Notice I don’t just call this.Close() again in the new TextBoxCompanyName_KeyDown event; but instead I call the ButtonOK_Click function to simulate the OK button being clicked. This way:

  • I don’t have duplicate code
  • I prevent a potential bug where if I had simply called this.Close() again, then someone in the future might add code to ButtonOK_Click and they might not know that TextBoxCompanyName_KeyDown will close the window a different way, leaving you in a weird state where the button does something that pressing “Enter” doesn’t do.

You now know how to do something different when you press “Enter”. I hope that was easy for you.


Copyright ® Rhyous.com – Linking to this page is allowed without permission and as many as ten lines of this page can be used along with this link. Any other use of this page is allowed only by permission of Rhyous.com.

3 Comments

  1. ssd cloud hosting

    Detecting when you press "Enter" in a WPF TextBox | Rhyous

  2. tomas says:

    good article, it helped mi a lot

  3. Sérgio says:

    Nice! Thank you.

Leave a Reply

How to post code in comments?