How to allow only plain text inside a RichTextBox in C#

By FoxLearn 2/14/2025 6:45:18 AM   40
By default, most rich text boxes do not support pasting text through drag and drop.

As a result, users can only add external content to your application using CTRL + V. To customize this behavior, we will modify the default paste action. Instead of pasting the text with its original formatting, we'll extract the plain text and insert it into the rich text box.

1. Add the KeyDown Event

The first step is to add an event listener to your existing Rich Text Box to handle the KeyDown event. You can do this through the events tab in the toolbox:

This will automatically generate the following method in your form class:

For example, KeyDown Event Richtextbox in C# WinForms

private void RichTextBox1_KeyDown(object sender, KeyEventArgs e)
{
}

In the next step, we will handle the event to customize the paste action.

2. Handle the Paste Event

Inside the KeyDown event listener, you need to check if the user pressed the key combination for paste (CTRL + V). If this condition is met, you can append the plain text from the clipboard to the current text in the rich text box. The Clipboard class makes it easy to retrieve the text as plain text:

private void RichTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.V)
    {
        richTextBox1.Text += (string) Clipboard.GetData("Text");
        e.Handled = true;
    }
}

Finally, mark the event as handled to prevent the default paste behavior.

With this setup, the CTRL + V paste action will insert plain text into the rich text box, overriding the default behavior.