I've 5 buttons in my windows application. When I click arrow keys the focus changing between buttons, then only
KeyUp
event firing. How to stop this?
I've 5 buttons in my windows application. When I click arrow keys the focus changing between buttons, then only
KeyUp
event firing. How to stop this?
Subscribe to the PreviewKeyDown
event instead.
Occurs before the KeyDown event when a key is pressed while focus is on this control.
As you move through the buttons, the sender
parameter will contain the previously selected button.
I found a solution that should work for you, adapted from here. Apparently, MS made the decision that the arrow keys wouldn't trigger the KeyDown
event, so you can't cancel them.
One workaround is to specify that your arrow keys are normal input keys, like any other key. Then the KeyDown
event will fire and you can cancel the button press if you want.
private void button1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Right || e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
e.IsInputKey = true;
}
private void button1_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
}
You may want to read the other answers and comments in that post to see what would work best in your situation.
Answer for your question in comment
void button1_LostFocus(object sender, EventArgs e)
{
button1.Focus();
}
To prevent Up from moving focus from a Button
you have to utilize at least 3 methods:
bool _focus;
private void button1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Up)
_focus = true;
}
private void button1_KeyUp(object sender, KeyEventArgs e)
{
_focus = false;
}
private void button1_Leave(object sender, EventArgs e)
{
if(_focus)
button1.Focus(); // or (sender as Control)
}
Trick is to use flag when user press Up and to return focus in Leave
. You have to unflag in KeyUp
, otherwise it would be impossible to change focus (by pressing Tab to example).
You could possible unflag in Leave
, I didn't test it.