KeyDown recognizes the left and right directional arrow keys, but not up and down

B. Clay Shannon picture B. Clay Shannon · May 9, 2012 · Viewed 12.1k times · Source

With the code below, the Left and Right arrow keys function as expected, but the up and down arrows are not recognized (stepping through it, the first two conditions are met where appropriate, but the second two never are):

private void textBox1_KeyDown(object sender, KeyEventArgs e) {
    TextBox tb = (TextBox)sender;

    if (e.KeyCode.Equals(Keys.Left)) {
        SetFocusOneColumnBack(tb.Name);
        e.Handled = true;
        return;
    }
    if (e.KeyCode.Equals(Keys.Right)) {
        SetFocusOneColumnForward(tb.Name);
        e.Handled = true;
        return;
    }
    if (e.KeyCode.Equals(Keys.Up)) {
        SetFocusOneRowUp(tb.Name);
        e.Handled = true;
        return;
    }
    if (e.KeyCode.Equals(Keys.Down)) {
        SetFocusOneRowDown(tb.Name);
        e.Handled = true;
        return;
    }
}

Why would this be, and how can I fix it?

UPDATE

Here's what I see when I hover over e.Keycode while stepping through. If I pressed

  • ...Left arrow key, I see: e.KeyCode = "LButton | MButton | Space"
  • ...Right arrow key, I see: e.KeyCode = "LButton | RButton | MButton | Space"
  • ...Up arrow key, I see: e.KeyCode = "RButton | MButton | Space"
  • ...Down arrow key, I see: e.KeyCode = "Backspace | Space"

This has got me baffled (what it's showing me), but on keyleft and keyright, my code is entered - it never is for keyup and keydown, no matter how hard I clench my teeth.

Answer

Hampus Nilsson picture Hampus Nilsson · May 9, 2012

Windows captures certain keys for UI navigation before they every get sent to your form. If you want to override this behavior you need to overload the IsInputKey method (and subclass the text field):

    protected override bool IsInputKey(Keys keyData)
    {
        if (keyData == Keys.Right)
            return true;
        return base.IsInputKey(keyData);
    }