问题
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