简体   繁体   English

C#从多个文本框中检测KeyPress事件中的文本框

[英]C# Detect textBox in KeyPress Event From Multiple textBoxes

I have 5 textBoxes which access the same KeyPressEvent() How do I detect from which textBox Currently key is Pressed ? 我有5个可访问相同KeyPressEvent()文本框,如何检测当前从哪个文本框按下了键?

 private void textBox_Department_KeyPress(object sender, KeyPressEventArgs e)
    {

       e.Handled = !(Char.IsLetter(e.KeyChar) | e.KeyChar == (char)Keys.Back | e.KeyChar==(char)Keys.Space);
    }

在事件签名中, object sender是调用KeyPress事件的对象(在您的情况下为TextBox)。

You could use the Tag property or even use x:Name and check if sender is equal to it. 您可以使用Tag属性,甚至可以使用x:Name并检查sender是否等于它。

For example, if you were to use tag, you could do this to your TextBox es. 例如,如果要使用标签,则可以对TextBox进行此操作。

<TextBox Tag="textBox1"../>

then in your code, you can cast sender to TextBox and check if it's tag is equal to whatever you want. 然后在您的代码中,可以将senderTextBox并检查其标签是否等于您想要的标签。

var textBox = (TextBox)sender;
if(textBox.Tag == "textBox1"){}

Or even better, check the sender itself: 甚至更好的是,检查发件人本身:

var textBox = (TextBox)sender;
if(textBox == myTextBoxNameInXName){}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM