How to Make RichTextBox Text Only?

Since RichTextBox doesn't have a Images or Objects collection you have to go for the RTF formatting codes. All data of RichTextBox is stored as plain text with special formatting codes, this is exposed by the control through its RTF property. Learning this code language is essential if you want to read or change it, learning resources are easily available throughout the web, see for example this overview. RichTextBox uses more simplified rtf codes than several full-feature editors like MS Word etc, so it is usually beneficial to load data into a RTB before manipulating it, this will remove much redundant data.

Making a long story short, I found that it is necessary to search for rtf groups that start with either "pict" or "object" command. Knowing that groups may be nested you can't just find the first end-group char from there, you have to parse the string char by char while keeping count of grouping to find the end of those groups. Now you have enough information to remove that part of the string. Rtf may contain multiple picture/object groups so you have to do this until all are removed. Here is a sample function that return rtf string after removing those groups:

private string removeRtfObjects(string rtf)
{
    //removing {\pict or {\object groups
    string pattern = "\\{\\\\pict|\\{\\\\object";
    Match m = Regex.Match(rtf, pattern);
    while (m.Success) {
        int count = 1;
        for (int i = m.Index + 2; i <= rtf.Length; i++) {
            //start group
            if (rtf(i) == '{') {
                count += 1;
            //end group
            } else if (rtf(i) == '}') {
                count -= 1;
            }
            //found end of pict/object group
            if (count == 0) {
                rtf = rtf.Remove(m.Index, i - m.Index + 1);
                break; // TODO: might not be correct. Was : Exit For
            }
        }
        m = Regex.Match(rtf, pattern);
        //go again
    }
    return rtf;
}

When should this be done? You have already mention Paste, there is also Insert, these can be trapped with the KeyDown event where you get the clipboard info and handle it accordingly. Setting e.Handled=True when you have handled the operation yourself signals that the control should not do any default processing for this key combination. This is also how you block pasting images without destroying the users clipboard. Example:

private void RichTextBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    //aware of Paste or Insert
    if (e.Control && e.KeyCode == Keys.V || e.Shift && e.KeyCode == Keys.I) {
        if (Clipboard.ContainsImage || Clipboard.ContainsFileDropList) {
            //some images are transferred as filedrops
            e.Handled = true;
            //stops here
        } else if (Clipboard.ContainsData(DataFormats.Rtf)) {
            RichTextBox rtbox = new RichTextBox();
            //use a temp box to validate/simplify
            rtbox.Rtf = Clipboard.GetData(DataFormats.Rtf);
            this.RichTextBox1.SelectedRtf = this.removeRtfObjects(rtbox.Rtf);
            rtbox.Dispose();
            e.Handled = true;
        }
    }
}

Yes, it is possible.

Handle Ctrl+V in RichTextBox1_KeyDown, then check the data format in the Clipboard: if data is plain text, paste it; if data is RTF, convert it to plain text (in a buffer without changing the Clipboard content) and paste it; don't paste any other type of data.

This is a partial example just to show you how to proceed:

private void richTextBox1_KeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.Control && e.KeyCode == Keys.V)  
    { 
            // suspend layout to avoid blinking
            richTextBox2.SuspendLayout();

            // get insertion point
            int insPt = richTextBox2.SelectionStart;

            // preserve text from after insertion pont to end of RTF content
            string postRTFContent = richTextBox2.Text.Substring(insPt);

            // remove the content after the insertion point
            richTextBox2.Text = richTextBox2.Text.Substring(0, insPt);

            // add the clipboard content and then the preserved postRTF content
            richTextBox2.Text += (string)Clipboard.GetData("Text") + postRTFContent;

            // adjust the insertion point to just after the inserted text
            richTextBox2.SelectionStart = richTextBox2.TextLength - postRTFContent.Length;

            // restore layout
            richTextBox2.ResumeLayout();

            // cancel the paste
            e.Handled = true;
    } 
} 

Comments

  1. Jasper

    • 2016/5/26

    Since RichTextBox doesn't have a Images or Objects collection you have to go for the RTF formatting codes. All data of RichTextBox is stored 

  2. Donovan

    • 2020/3/18

    Handle Ctrl+V in RichTextBox1_KeyDown, then check the data format in the Clipboard: if data is plain text, paste it; if data is RTF, convert it to plain text (in a buffer without changing the Clipboard content) and paste it; don't paste any other type of data. This is a partial example just to show you how to proceed:

  3. Zachariah

    • 2019/5/18

    By default, not any rich text box allows to paste text via drag and drop, so the only way that the user will have to add external content 

  4. Sanders

    • 2019/8/5

    For example, a hyper link is copied from IE and when it is pasted to the RichTextBox, it shows like a plain text. This can be easily achieved by using TextBox, but we have to use RichTextBox in this particular case. Thanks. Friday, February 20, 2009 5:46 AM. Tao Liu.

  5. Raphael

    • 2015/8/13

    This example shows how to extract the contents of a RichTextBox as plain text. Example. The following Extensible Application Markup Language ( 

  6. Kaiser

    • 2020/9/11

    If you see an error about incompatible rich-text settings in the Design Checker task pane, select the Enable browser-compatible settings only check box in the Rich Text Box Properties dialog box. Doing so automatically selects the correct rich-text settings for you. A subscription to make the most of your time.

  7. Fabian

    • 2021/5/26

    To get the rich text formatting (RTF) codes, use the Rtf property. The amount of text that can be entered in the RichTextBox control is limited only by 

  8. Dario

    • 2020/12/16

    In the Internet Format list, click Send Plain Text only or Send using Outlook Rich Text format. By default, Let Outlook decide the best sending format is selected, which usually is HTML format. Note: You can change the format for only the messages sent to a contact with an SMTP email address.

  9. Paul

    • 2015/5/15

    A RichTextBox control is an advanced text box that provides text editing You can make a RichTextBox control read-only (non-editable) by 

  10. Parker

    • 2021/6/8

    The first step to create a dynamic RichTextBox is to create an instance of the RichTextBox class. The following code snippet creates a RichTextBox control object. RichTextBox dynamicRichTextBox = new RichTextBox (); In the next step, you may set properties of a RichTextBox control.

  11. Desmond

    • 2017/5/19

    How can you strip all formatting from a formatted text copied to the clipboard and paste it as plain text on the rich textbox?

  12. Robin

    • 2016/4/1

    using System; using System.Drawing; using System.IO; using System.Windows.Forms; public partial class Form1: Form { internal RichTextBox RichTextBox1; internal Button Button1; internal RichTextBox RichTextBox2; internal Button Button2; internal SaveFileDialog SaveFileDialog1; public Form1() : base() { this.RichTextBox1 = new RichTextBox(); this.Button1 = new Button(); this.RichTextBox2 = new RichTextBox(); this.Button2 = new Button(); this.SaveFileDialog1 = new SaveFileDialog(); this

  13. Emiliano

    • 2017/6/24

    To format text in a RichTextBox, use the control's Select method to select the text. Then use the “Selection” properties (SelectionAlignment 

  14. Kaison

    • 2020/6/4

    Private Sub WriteCenteredTextToRichTextBox() ' Clear all text from the RichTextBox; richTextBox1.Clear() ' Set the foreground color of the text. richTextBox1.SelectionColor = Color.Red ' Set the alignment of the text that follows. richTextBox1.SelectionAlignment = HorizontalAlignment.Center ' Set the font for the text.

  15. Alejandro

    • 2016/4/5

    Rich text boxes enable the user to enter and edit formatted text at runtime. Thus, the user can benefit from all format options that have been provided by 

  16. Jaziel

    • 2015/2/9

    The copied HTML may not only affect the pasted text but also other text on the page in UVACollab where it appears. For example, if content from 

  17. Bobby

    • 2019/7/18

    One is a 'Plain Text (TXT format)' format and the other one is 'Rich Text Format (RTF format)'. In this article, we will have a look 

Comments are closed.

Recent Posts