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

时间:2014-10-13 13:51:44

标签: 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, KeyPressEventArgs e)
{
    if(e.KeyChar == '\r')
    {
        e.Handled = true;
        // some other stuff
    }
}

有没有办法将keypress事件动态连接到聚焦文本框?

修改

类似的东西:

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

1 个答案:

答案 0 :(得分:2)

你可以这样做:

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
    }
}