如何发送文本框作为 KeyDown 函数 c# 的参数?

How to send a textbox as a parameter for KeyDown function c#?

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

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

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)

Dmitry Bychenko 给出的答案有你需要的基础。但是如果你想总是 select next 文本框,你首先需要某种顺序的列表并将其填写到你的 class 构造函数中:

private TextBox[] textBoxOrder;

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

然后在您的关键侦听器中,您可以对 select 下一个执行以下操作:

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();