【问题标题】:How to Interpret an Enter KeyPress as a Tab in C#如何在 C# 中将 Enter KeyPress 解释为选项卡
【发布时间】:2011-06-05 08:17:23
【问题描述】:

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

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

【问题讨论】:

  • 值得注意的是,这不是 Windows 中的标准行为。覆盖它不仅会使您的用户感到困惑,而且尝试覆盖默认值总是比仅仅像您的平台期望您采取行动那样做更多的工作。这样的代码很容易成为维护的噩梦,其中潜伏着奇怪的错误。

标签: c# .net winforms keypress


【解决方案1】:

欢迎来到 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;
    }
} 

这实际上允许用户按“Shift+Enter”也可以转到继续选项卡。

选项 2:使用SendKeys 方法

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

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

【讨论】:

  • 我个人肯定会推荐选项 2。结果对我来说要容易得多,无论如何,这种行为正是我们在这种情况下所要寻找的。谢谢!
【解决方案2】:

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

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

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

【讨论】:

  • @Cody- 可悲的是我实际上想过自己这样做,但只是因为 ToolStripBar 控件默认没有 TabStop 属性,我们最终只是摆脱了 ToolStrip (我们是在一个可能的阶段)。
  • @Ramhound:那是因为ToolStrip/ToolStripMenuBar 上的项目无法获得焦点。无论项目处于哪个阶段,您都会发现您需要摆脱它并改变您的设计。
【解决方案3】:

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

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

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

【讨论】:

    【解决方案4】:
    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);
             }
           }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-22
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多