【问题标题】:How to send a textbox as a parameter for KeyDown function c#? [closed]如何发送文本框作为 KeyDown 函数 c# 的参数? [关闭]
【发布时间】:2016-04-11 12:22:23
【问题描述】:

我有 10 个文本框。我想要一个通用的 KeyDown 函数,以便在调用它时发送参数。我在 textbox1 中输入了一些文本,然后按“Enter”键,然后光标聚焦发送文本框(例如:textbox2),我在 KeyDown 函数调用时作为参数发送。

private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if(e.KeyCode == Keys.Enter)
        {
            textBox2.Focus();
        }
    }

【问题讨论】:

  • 请阅读help center,尤其是How to Ask
  • 呃。几乎所有 C# 中的侦听器已经包含 object sender...
  • @Nyerguds 我想他是说在textBox1 的舔事件中,他想传递一个文本框而不是它自己,例如textBox2 作为参数
  • @AlfieGoodacre 除非是固定的轮换顺序,否则几乎不可能;在这种情况下,答案是简单地将它们全部放在某个全局数组中并检查您当前所在的数组。

标签: c# function parameters textbox


【解决方案1】:

TextBox 实例通过sender 参数发送:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    TextBox textBox = sender as TextBox;

    if (e.KeyCode == Keys.Enter)
    {
        // if we can focus:
        //   1. it's a textbox instance that has called Key Down event
        //   2. the textbox can be focused (it's visible, enabled etc.)  
        // then set keyboard focus  
        if ((textBox != null) && textBox.CanFocus) 
        {
            textBox.Focus();
            // you may find useful not proceeding "enter" further
            e.Handled = true; 
        }
    }
}

请确保您已为所有感兴趣的文本框分配了相同 textBox1_KeyDown 方法 (textBox1...textBox10)

【讨论】:

    【解决方案2】:

    Dmitry Bychenko 给出的答案有你需要的基础。但是,如果您想始终选择 next 文本框,则首先需要某种该顺序的列表并将其填充到您的类构造函数中:

    private TextBox[] textBoxOrder;
    
    public Form Form1()
    {
        InitializeComponent();
        textBoxOrder = new TextBox[]
        {
            textBox1, textBox2, textBox3, textBox4, textBox5,
            textBox6, textBox7, textBox8, textBox9, textBox10
        };
    }
    

    然后在您的关键监听器中,您可以执行以下操作来选择下一个:

    TextBox nextBox = null;
    for (Int32 i = 0; i < textBoxOrder.Length; i++)
    {
        if (textBoxOrder[i] == sender)
        {
            if (i + 1 == textBoxOrder.Length)
                nextBox = textBoxOrder[0]; // wrap around to first element
            else
                nextBox = textBoxOrder[i + 1];
            break;
        }
    }
    if (nextBox != null)
        nextBox.Focus();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 2020-11-28
      • 2013-07-01
      • 1970-01-01
      相关资源
      最近更新 更多