5

How do I prevent the caret going to the next line in a text box when the 'ENTER' key has been pressed? In other words how to disable the 'ENTER' or 'RETURN' key in a text-box?

MikeD
  • 5,004
  • 1
  • 25
  • 39

2 Answers2

12

You can write the OnKeyDown event. you can use the e.SuppressKeyPress to tell .NET that you handle the key. Something like this:

if (e.KeyCode == Keys.Enter) {
    e.SuppressKeyPress = true;
}
bluish
  • 26,356
  • 27
  • 122
  • 180
Jedi Master Spooky
  • 5,629
  • 13
  • 57
  • 86
  • +1 for useful information for the general case even if it's not the best approach for this particular scenario – Davy8 Mar 13 '09 at 18:46
  • WOW fast reply... this is way better than other forums (don't want to say which ones) where people insult people who ask questions. Thanks, thanks. –  Mar 13 '09 at 20:27
  • KeyPressEventArgs doesn't contains SuppressKeyPress... I am using OnKeyPress event –  Mar 13 '09 at 20:30
  • If you want to suppress de key you would have to use OnKeyDown – Jedi Master Spooky Mar 13 '09 at 23:44
6

Take a look at TextBox.AcceptsReturn.

bluish
  • 26,356
  • 27
  • 122
  • 180
Jakob Christensen
  • 14,826
  • 2
  • 51
  • 81