Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将单个按键事件连接到具有焦点的控件_C#_Focus_Controls_Keypress - Fatal编程技术网

C# 将单个按键事件连接到具有焦点的控件

C# 将单个按键事件连接到具有焦点的控件,c#,focus,controls,keypress,C#,Focus,Controls,Keypress,我有两个文本框,每个文本框都附带有自己的按键事件 private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if(e.KeyChar == '\r') { e.Handled = true; // some other stuff } } private void textBox2_KeyPress(object sender, KeyPressEventArg

我有两个文本框,每个文本框都附带有自己的按键事件

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if(e.KeyChar == '\r')
    {
        e.Handled = true;
        // some other stuff
    }
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
    if(e.KeyChar == '\r')
    {
        e.Handled = true;
        // some other stuff
    }
}
有没有办法将按键事件动态连接到聚焦文本框

编辑

比如:

void KeyPress(object sender, KeyPressEventArgs e)
{
    foreach(Control c in this)
    {
        if(c == TextBox && c.Focused)
        {
            if(e.KeyChar == '\r')
            {
                // do something
            }
        }
    }
}
你可以这样做:

textBox1.KeyPress += new KeyPressEventHandler(textBox_KeyPress);
textBox2.KeyPress += new KeyPressEventHandler(textBox_KeyPress);

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if(e.KeyChar == '\r')
    {
        e.Handled = true;
        // some other stuff
        Console.WriteLine(((TextBox)sender).Name); //actual textbox name
    }
}

foreach(这里是控制c)永远不要这样做^^Naaa,这只是伪代码^^^看我的答案,这就是要做的事这就是要做的事。谢谢