如何解释输入KeyPress作为C#中的选项卡

2 .net c# keypress winforms

我刚刚开始进行C#开发,我正在开发一个基于表单的项目,当用户在表单上并按下Enter键时,我正在尝试执行"tab"操作.

我知道答案可能很简单,但我是这个领域的新手.

Rio*_*ams 11

欢迎来到SO Tex,

我相信有两种方法可以实现这一点,只需要添加:

选项1:如果执行了Enter KeyPress,则抓取下一个控件

在表单的属性中,将表单的KeyPreview属性设置为true.

下面的代码将捕获您的"Enter-Press"事件并执行您要查找的逻辑:

private void [YourFormName]_KeyDown(object sender, KeyEventArgs e)
{
    Control nextControl ;
    //Checks if the Enter Key was Pressed
    if (e.KeyCode == Keys.Enter) 
    {
        //If so, it gets the next control and applies the focus to it
        nextControl = GetNextControl(ActiveControl, !e.Shift);
        if (nextControl == null)
        {
            nextControl = GetNextControl(null, true);
        }
        nextControl.Focus();
        //Finally - it suppresses the Enter Key
        e.SuppressKeyPress = true;
    }
} 
Run Code Online (Sandbox Code Playgroud)

这实际上允许用户按"Shift + Enter"以进入前进选项卡.

选项2:使用SendKeys方法

private void [YourFormName]_KeyDown(object sender, KeyEventArgs e)
{
  if (e.KeyCode == Keys.Enter)
  {
     SendKeys.Send("{TAB}");
  }
}
Run Code Online (Sandbox Code Playgroud)

我不确定这种方法是否仍然常用或者可能被视为"黑客"?我会推荐第一个,但我相信两者都应该满足您的需求.