Disable jumping between buttons by using arrow keys

有些话、适合烂在心里 提交于 2021-01-20 09:04:05

问题


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.

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?

Thank you!


回答1:


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.

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);
}


来源:https://stackoverflow.com/questions/65471069/disable-jumping-between-buttons-by-using-arrow-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!