简体   繁体   English

C#中的按键事件

[英]Key press event in C#

I want to code a key press event to a text box to accept only alphabets.. any help appreciated. 我想将按键事件编码到文本框中以仅接受字母..任何帮助。

also, the different validations that I can apply to a normal textbox to not accept anything else than alphabets. 同样,我可以应用于普通文本框的其他验证方式不接受除字母以外的任何内容。 even if copy pasted and not just key press// 即使复制粘贴而不仅仅是按键//

thanks reggie 谢谢雷吉

You need TextChanged event. 您需要TextChanged事件。 You might also want to check MaskedTextBox control. 您可能还需要检查MaskedTextBox控件。

Use a maskedtextbox control. 使用maskedtextbox控件。 That will solve your problem. 那将解决您的问题。

http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask.aspx http://msdn.microsoft.com/zh-CN/library/system.windows.forms.maskedtextbox.mask.aspx

hook up the event on the textbox: 在文本框中挂接事件:

private void txtBOX_KeyPress(object sender, KeyPressEventArgs e)
{

}

You can use textchange event, or a mask. 您可以使用textchange事件或掩码。 keypress as mention above is the ugliest way to do it, but the most powerfull.. you can "play" with the input data as you wish. 上面提到的keypress是最丑陋的方式,但是最强大的..您可以根据需要“播放”输入数据。

use these code in your key press event 在按键事件中使用这些代码

if(!char.IsLetter(e.keyChar) && e.keyChar!=8)
{
e.handeled=true;
}  

These will prevent your text box to accept any thing else alphabets and the backspace button. 这些将阻止您的文本框接受其他任何字母和退格按钮。

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

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