使用箭头键禁用按钮之间的跳转 [英] Disable jumping between buttons by using arrow keys
问题描述
我有一个上面带有 TableLayoutPanel
的WinForms表单.在此TableLayoutPanel中,我有2个 Button
控件.
I have a WinForms form with a TableLayoutPanel
on it.
In this TableLayoutPanel, I have 2 Button
controls.
我按下这些按钮之一.然后按键盘上的向上或向下箭头(↑ ↓).
I press one of these buttons. Then I press the Up or Down arrow (↑ ↓) on the keyboard.
焦点从一个按钮跳转到另一个按钮.
The focus jumps from one button to the other.
我不要这种行为.设置TableLayoutPanel的"TabStop".为假"没有帮助.
I don't want this behaviour. Setting the TableLayoutPanel's "TabStop" to "False" doesn't help.
我想拦截事件并将焦点手动设置为另一个控件.但是,我没有找到需要拦截的事件.
I would instead like to intercept the event and set the focus to another control manually. However, I didn't find the event that I need to intercept.
如何禁用箭头键跳转?我必须拦截哪个事件才能将焦点设置到另一个控件?
How could I disable this jumping by arrow keys? Which event would I have to intercept to set the focus to another control?
谢谢!
推荐答案
You can handle PreviewKeyDown
event of all the buttons using a single handler and check if the pressed key is an arrow key, set e.IsInputKey = true
and prevent focus change:
private void button1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
var keys = new[] { Keys.Left, Keys.Right, Keys.Up, Keys.Down };
if (keys.Contains(e.KeyData))
e.IsInputKey = true;
}
You can read about the behavior and the solution in Remarks section of the PreviewKeyDown
documentations.
该行为实际上是在容器控件的 ProcessDialogKey
方法中实现的(您可以看到
The behavior is in fact implemented in ProcessDialogKey
method of the container control (you can see source code) and you can also prevent it by overriding ProcessDialogKey
of the Form
, like this:
protected override bool ProcessDialogKey(Keys keyData)
{
var keys = new[] { Keys.Left, Keys.Right, Keys.Up, Keys.Down };
if (keys.Contains(keyData))
return true;
else
return base.ProcessDialogKey(keyData);
}
这篇关于使用箭头键禁用按钮之间的跳转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!