【问题标题】:C# Winform Alter Sent KeystrokeC# Winform 更改发送按键
【发布时间】:2009-06-13 12:51:33
【问题描述】:

您好,我有一个 C# winform 应用程序,其中包含一个填充了许多文本框的特定表单。我想让它通过按右箭头键来模仿与按 Tab 键相同的行为。我不确定该怎么做。

我根本不想改变 tab 键的行为,只要在那个表单上用右箭头键做同样的事情。

谁能给点建议?

【问题讨论】:

    标签: c# winforms key


    【解决方案1】:

    您应该覆盖表单中的 OnKeyUp 方法来执行此操作...

    protected override void OnKeyUp(KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Right)
        {
           Control activeControl = this.ActiveControl;
    
           if(activeControl == null)
           {
                activeControl = this;
           }
    
           this.SelectNextControl(activeControl, true, true, true, true);
           e.Handled = true;
        }
    
        base.OnKeyUp(e);
    }
    

    【讨论】:

    • 嗨,Brian,这似乎工作正常,但它只遍历它所在的容器上的控件 - 例如 - 组框。所以如果我有 3 个带有控件的组框,它不会像 tab 键那样跳到下一个
    • 我将更新它以使用 SelectNext,我认为它确实可以在容器上递归地工作。
    【解决方案2】:

    您可以使用表单上的 KeyDown 事件来捕获击键,然后执行您想要的任何操作。例如:

     private void MyForm_KeyDown(object sender, KeyEventArgs e)
     {
         if(e.KeyCode == Keys.Right)
         {
             this.SelectNextControl(....);
             e.Handled = true;
         }
     }
    

    不要忘记将表单上的 KeyPreview 属性设置为 True。

    【讨论】:

    • 我会重写方法而不是使用事件。另外,我不会在 KeyDown 上执行此操作,您应该真正在按键向下和向上之间进行跟踪,以确保您有相关的完整按键。
    【解决方案3】:

    我认为这将完成您的要求:

    private void form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Right)
        {
            Control activeControl = form1.ActiveControl;
            // may need to check for null activeControl
            form1.SelectNextControl(activeControl, true, true, true, true);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      • 2019-04-05
      • 1970-01-01
      • 2011-03-14
      • 1970-01-01
      • 1970-01-01
      • 2015-03-07
      相关资源
      最近更新 更多