【问题标题】:connect a single key event to the control that has focus将单个键事件连接到具有焦点的控件
【发布时间】:2014-12-08 02:47:13
【问题描述】:

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

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

【问题讨论】:

  • foreach(Control c in this) 永远不要那样做^^
  • Naaa,这只是伪代码^^
  • 看我的回答,这就是办法

标签: c# focus controls keypress


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 这是要走的路。谢谢!
猜你喜欢
  • 2017-05-08
  • 1970-01-01
  • 2015-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-30
  • 1970-01-01
相关资源
最近更新 更多