使用Enter键更改用户控件中文本框的焦点

时间:2019-06-06 12:09:43

标签: c# winforms

我正在使用包含多个UserControl控件的自定义TextBoxe,请参见下文:

enter image description here

我希望能够使用Enter键在TextBoxe中的UserControl控件之间移动。

但是,当我将UserControl放在表单上并在第一个Enter(“形状”)具有焦点之后按TexTbox键时,焦点将放在下一个UserControl之后的表格控制。它将跳过“ Dim1”到“其他” TextBoxe控件。我可以使用Tab键,它会按预期在每个TextBoxe中移动。我尝试使用不同的按键事件,并且当它们捕获某些键(即字母和数字)时,它们似乎并没有捕获Enter键。

任何有关如何实现此目标的帮助/指导都将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以将KeyDown事件捕获到Enter,并将其发送给用户控件中的所有文本框,以按制表顺序依次执行下一个文本框:

private void textBox_KeyDown(object sender, KeyEventArgs e)
{
    Control textbox = sender as TextBox;
    if (textbox != null) // Safety check
    {
        if (e.KeyCode == Keys.Enter)
        {
            // Check if next control is a text-box and send focus to it.
            Control nextControl = GetNextControl(textbox, true);
            if (nextControl is TextBox)
            {
                SelectNextControl(textbox, true, true, false, false);
            }
        }
    }
}

为避免Hans Passant引起事件订阅,您可以覆盖ProcessCmdKey

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    Control control = ActiveControl as TextBox;
    if (control != null) // Safety check
    {
        if (keyData == Keys.Enter)
        {
            // Check if next control is a text-box and send focus to it.
            Control nextControl = GetNextControl(control, true);
            if (nextControl is TextBox)
            {
                SelectNextControl(control, true, true, false, false);
            }
        }
    }

    return base.ProcessCmdKey(ref msg, keyData);
}
相关问题