Input handling in WinForm

What is the best way to block certain input keys from being used in a TextBox with out blocking special keystrokes such as Ctrl-V/Ctrl-C?

For example, only allowing the user to enter a subset of characters or numerics such as A or B or C and nothing else.


I would use the keydown-event and use the e.cancel to stop the key if the key is not allowed. If I want to do it on multiple places then I would make a user control that inherits a textbox and then add a property AllowedChars or DisallowedChars that handle it for me. I have a couple of variants laying around that I use for time to time, some allowing money-formatting and input, some for time editing and so on.

The good thing to do it as a user control is that you can add to it and make it to your own killer-text-box. ;)


I used the Masked Textbox control for winforms. There's a longer explanation about it here. Essentially, it disallows input that doesn't match the criteria for the field. If you didn't want people to type in anything but numbers, it simply would not allow them to type anything but numbers.


This is how I handle this usually.

Regex regex = new Regex("[0-9]|b");            
e.Handled = !(regex.IsMatch(e.KeyChar.ToString()));

That will only allow numerical characters and the backspace. The problem is that you will not be allowed to use control keys in this case. I would create my own textbox class if you want to keep that functionality.

链接地址: http://www.djcxy.com/p/95956.html

上一篇: 如何防止按键更新MaskedTextBox的文本?

下一篇: WinForm中的输入处理