Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 235
benPearce Avatar asked Dec 31 '22 08:12

benPearce


2 Answers

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. ;)

like image 147
Stefan Avatar answered Jan 01 '23 20:01

Stefan


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.

like image 22
George Stocker Avatar answered Jan 01 '23 21:01

George Stocker