[英]KeyUp event firing from next control
I've 5 buttons in my windows application. 我的Windows应用程序中有5个按钮。 When I click arrow keys the focus changing between buttons, then only
当我单击箭头键时,焦点将在按钮之间切换,然后仅
KeyUp
KEYUP
event firing. 事件触发。 How to stop this?
如何停止呢?
Subscribe to the PreviewKeyDown
event instead. 而是订阅
PreviewKeyDown
事件。
Occurs before the KeyDown event when a key is pressed while focus is on this control.
当焦点位于此控件上时,在按下键时在KeyDown事件之前发生。
As you move through the buttons, the sender
parameter will contain the previously selected button. 在按钮之间移动时,
sender
参数将包含先前选择的按钮。
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. 显然,MS决定箭头键不会触发
KeyDown
事件,因此您无法取消它们。
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. 然后,将触发
KeyDown
事件,并且您可以根据需要取消按钮的按下。
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: 为了防止Up从
Button
上移动焦点,您必须至少使用3种方法:
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
. 技巧是在用户按下向上键时使用标志,并在“
Leave
返回焦点。 You have to unflag in KeyUp
, otherwise it would be impossible to change focus (by pressing Tab to example). 您必须在
KeyUp
取消KeyUp
,否则将无法更改焦点(通过按Tab进入示例)。
You could possible unflag in Leave
, I didn't test it. 您可以在
Leave
取消标记,但我没有对其进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.