Reputation: 10247
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?
Here's what I see when I hover over e.Keycode while stepping through. If I pressed
e.KeyCode = "LButton | MButton | Space"
e.KeyCode = "LButton | RButton | MButton | Space"
e.KeyCode = "RButton | MButton | Space"
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.
Upvotes: 6
Views: 12856
Reputation: 521
Well too late for the party but if anyone is interested, use e.KeyValue
instead, as an example, e.KeyValue
for left arrow key is 37
and for right arrow key 39
and so on.
Upvotes: 1
Reputation: 57
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;
}
}
Upvotes: 1
Reputation: 10247
I find that using the PreviewKeyDown does work (I had to remove the "e.Handled = true" code, as it doesn't 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, three different events were needed to handle the various keys I was looking for: KeyPress for regular characters, KeyDown for non-characters (left and right arrow keys) and this one (PreviewKeyDown) for the up and down arrow keys.
Upvotes: 3
Reputation: 6822
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);
}
Upvotes: 4