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
  • 4,854
  • 1
  • 23
  • 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
  • 24,718
  • 26
  • 114
  • 174
Jedi Master Spooky
  • 5,371
  • 11
  • 52
  • 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
  • 24,718
  • 26
  • 114
  • 174
Jakob Christensen
  • 14,561
  • 1
  • 50
  • 81