C# - 允许使用箭头键切换输入字段

时间:2016-05-25 11:39:26

标签: c# textbox controls

我有一个C#Windows窗体应用程序,它使用10个文本框作为输入字段,我希望能够对这些文本框进行编程,以便无论哪个文本框具有焦点,都可以使用向上箭头(Keys.Up)或向下箭头(可以按下Keys.Down),焦点将跳转到下一个或上一个文本框。

到目前为止,我打算使用这样的东西:

        if (e.KeyChar == Convert.ToChar(Keys.Up))
        {
            GetNextControl((TextBox)sender, false);
        }
        else if (e.KeyChar == Convert.ToChar(Keys.Down))
        {
            GetNextControl((TextBox)sender, true);
        }

我唯一担心的是这是否会干扰实际文本的输入。上面的代码是否需要更改为类似下面的代码?

        if (e.KeyChar == Convert.ToChar(Keys.Up))
        {
            GetNextControl((TextBox)sender, false);
        }
        else if (e.KeyChar == Convert.ToChar(Keys.Down))
        {
            GetNextControl((TextBox)sender, true);
        }
        //any other key pressed
        else
        {
            TextBox input = (TextBox)sender;
            //add char relating to pressed key to text in TextBox
            input.AppendText(e.KeyChar.ToString());
        }

是否需要此else子句或TextBox的默认操作是否处理此条件?

谢谢, 标记

2 个答案:

答案 0 :(得分:1)

Up 键的e.KeyChar是多少?请勿使用char,而是使用密钥代码:

private void myTextBoxes_KeyDown(object sender, KeyEventArgs e) {
  // KeyCode: there're no reasonable chars after "Up" or "Down" keys
  if (e.KeyCode == Keys.Up) {
    e.Handled = true; // to prevent system processing

    // (Control): what if you want to add, say, RichEdit into the pattern? 
    GetNextControl((Control) sender, false);
  }
  else if (e.KeyCode == Keys.Down) {
    e.Handled = true; // to prevent system processing

    GetNextControl((Control) sender, true);
  }
}

答案 1 :(得分:1)

听起来像个好计划。对于你的例子,它将起作用。

为了使它更通用(不仅适用于文本框),我建议您阅读 PreviewKeyDown 事件(理由:在某些控件中,向上/向下键不会触发KeyDown事件,尽管它适用于文本框)。

对于GetNextControl,使用 FindForm()。SelectNextControl()可能会有所帮助,因为它可以更精细地控制跳过的内容。

P.S。另外...... GetNextControl将返回控件。但不会跳到它。你必须向它添加.Focus()。