Just recently I had to deal with WinForms for the first time in a long while and I stumbled upon an interesting thought. How would I go about making a custom WinForms TextBox with some kind of ‘uncommon behaviour’? I dug deeper into this subject, did some research on it and I think I have come up with something that is worth sharing.
As far as simple WinForms projects are concerned, customising behaviour of their controls can be done easily. However, if your project requires some TextBoxes to work traditionally and others to have been inbuilt with some validation logic, I suggest you follow the steps described in this piece.
I am going to demonstrate this on a project, where every ‘a’ entered into a text box will become a ‘b’.
To kick things off, create a WinForms project and name it whatever you want (I named mine CustomWinFormsTextBox).
Then right-click your project in the Solution Explorer and add a new class. I have chosen CustomTextBox as it’s name.
After the class is successfully created, make it a child of TextBox. Then in order to add the described behaviour, override the OnKeyPress method of the TextBox class. This method is called everytime we press a key on the keyboard while the TextBox is focused.
We are essentially checking if an ‘a’ has been pressed, in which case we would replace it with a ‘b’, that would then get displayed in the text box.
Now all that’s left to do is to add our CustomTextBox to the Toolbox window so that we can drag-and-drop it onto our form. The Toolbox won’t offer you custom control just yet. First you have to build your solution. Then if you search for CustomTextBox you should see it appear in the search results.
Now just simply drag and drop it onto the form, save your project and hit Start. If you try to enter ‘maniac’, the text box will show ‘mbnibc’.
Although I know this won’t come to good use to everyone, I still think it is worth knowing about it.