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

时间:2011-01-07 15:14:35

标签: c# .net winforms keypress

我刚刚开始使用C#开发,我正在开发基于表单的项目,当用户在表单上并按下Enter键时,我正尝试执行“tab”操作。

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

4 个答案:

答案 0 :(得分:11)

欢迎来到SO Tex,

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

选项1:如果执行了输入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;
    }
} 

这实际上允许用户按“Shift + Enter”以转到进行中的标签。

选项2:使用SendKeys方法

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

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

答案 1 :(得分:1)

首先,准备一个Dictionary of,其中键是第一个控件,值是第二个。遍历Form的Control集合中的所有控件,通过TabIndex将它们放入排序列表中,并将其转换为Dictionary。

您需要KeyPress事件中的每个对象的代码,或子类TextBox以包含此逻辑。无论哪种方式,在KeyPress事件中,如果输入为Enter,请从字典中获取以下控件并使用Control.GetFocus()。

希望有所帮助!如果您愿意,我可以提供更多细节。

答案 2 :(得分:0)

您可以使用Application.AddMessageFilter和IMessageFilter接口在表单级别和完整的应用程序级别处理键盘事件。

所有这些事件都有“已处理”属性,如果您手动处理某些键,则可以将其设置为“True”。 (在你的情况下输入密钥)。

以下是如何捕获两个级别的关键事件的示例:Keyboard event handling in .NET applications

答案 3 :(得分:0)

private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)  
{
        SendKeys.Send("{UP}");
        SendKeys.Send("{Right}");
}

private void onEnterKeyPress(object sender, KeyPressEventArgs e)
{

      if (sender is DataGridView)
      {
         int iColumn = DataGridView1.CurrentCell.ColumnIndex;
         if (iColumn == DataGridView1.Columns.Count - 1)
         {
               SendKeys.Send("{home}");
         }
         else
         {

               this.ProcessTabKey(true);
         }
       }
}