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,这只是伪代码^^^看我的答案,这就是要做的事这就是要做的事。谢谢