Search code examples
c#overridingrichtextbox

C# RichTextBox Form- Want to manipulate User Input Before Displaying it


I have a RichTextBox Form in C#. What I want to do is take the user input and perform some type of text manipulation on it before displaying it in the textbox.

For example - user types "1 2 3". My method ignores all text but 3, and only displays 3 in the textbox.

My question is, is there a user input method in RichTextBox (or something similar) that I can override and place my functionality in? Or will I have to brute force it and literally look out for key events and assign my method results RichTextBox.Text afterwards?


Solution

  •         List<char> allowedChars = new List<char>() { '3' };
            private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
            {
                if (!allowedChars.Contains(e.KeyChar))
                    e.Handled = true;
            }