0
  • I have a textbox
  • User enters some value
  • User presses Enter
  • System does some stuff

A pretty standard sequence of actions and I was wondering whether to use the KeyDown or KeyUp-event. Now, almost all examples I found on this, used the KeyDown event to detect whether the enter-key has been pressed. However, according to this article, the KeyDown event is triggered multiple times when a key is held down for a while. Which raises my question: why would I use KeyDown? My event will be triggered multiple times if the user accidentally holds down the enter-key, which is not something I want.

Is there some reason why I would use KeyDown over KeyUp?

Community
  • 1
  • 1
JeroenM
  • 117
  • 1
  • 9
  • No, there is no reason to use KeyDown over KeyUp in this case. But I don't know why you'd want to trap Enter in a TextBox. This is supposed to move to the next line. – Cody Gray - on strike Aug 08 '14 at 10:51

2 Answers2

4

Well, it matters. If you use KeyUp then you'll have to deal with also getting the KeyPress event for the Enter key. Which, it not intercepted, produces a nasty BEEP to slap the user. Boilerplate is to always use KeyDown so you can stop the KeyPress event from firing:

    private void textBox1_KeyDown(object sender, KeyEventArgs e) {
        if (e.KeyData == Keys.Enter) {
            e.Handled = e.SuppressKeyPress = true;
            // Something special ...
            //...
        }
    }

The SuppressKeyPress assignment prevents the KeyPress event from firing.

Do keep in mind that handling Enter is normally fairly gauche and indicates that you might be trying too hard to make your GUI resemble a console mode app. What Enter is supposed to do is operate the default accept button on a window. Supported by the Form.AcceptButton property. The Escape key is special that way as well, it operates the Form.CancelButton button. Only truly meaningful things to do for a dialog-style window however.

If used on a regular window then the typical problem is that the user has no idea that pressing the Enter key is what he's supposed to do. He'll mouse to another textbox and completely miss the intended usage of your UI design, that's a problem with discoverability. You can't do the equivalent of ToolStripMenuItem.ShortcutKeyDisplayString in this case.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
0

You can add some boolean field (enterInProcessed) and check:

 if (e.KeyCode == Keys.Enter && !enterProcessed){
     enterProcessed = true; 
     ...
 }
 enterProcessed = false;

To prevent processing of the event multiple times.

Roman Bats
  • 1,775
  • 3
  • 30
  • 40