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

Using the code below, the left and right arrow keys function as expected, but the up and down arrows are not recognized (passing through it, the first two conditions are met where necessary, but never in the second):

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 is this and how can I fix it?

UPDATE

Here is what I see when I hover over e.Keycode when going through. If i clicked

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

It puzzled me (what it shows me), but on keyleft and keyright my code is entered - it is never used for keyup and keydown, no matter how hard I grit my teeth.

+6
source share
4 answers

I found that using PreviewKeyDown really works (I had to remove the code "e.Handled = true" since it does not apply in the PreviewKeyDown event):

 private void textBoxQH1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { TextBox tb = (TextBox)sender; if (e.KeyCode.Equals(Keys.Up)) { SetFocusOneRowUp(tb.Name); return; } if (e.KeyCode.Equals(Keys.Down)) { SetFocusOneRowDown(tb.Name); return; } } 

So, to handle the various keys I was looking for, I needed three different events: KeyPress for regular characters, KeyDown for non-characters (left and right arrow keys) and this (PreviewKeyDown) for up and down arrow keys.

+3
source

Windows captures certain keys for navigating the user interface before they are submitted to your form. If you want to override this behavior, you need to overload the IsInputKey method (and a subclass of the text field):

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

You can use this code:

 private void TextBox1_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Up: //Do stuff break; case Keys.Down: //Do stuff break; case Keys.Left: //Do stuff break; case Keys.Right: //Do stuff break; } } 
+1
source

It's too late for a party, but if anyone is interested, use e.KeyValue instead, as an example, e.KeyValue for the left arrow key 37 and for the right arrow key 39 , etc.

+1
source

Source: https://habr.com/ru/post/915302/


All Articles