How to Make RichTextBox Text Only? [duplicate]

2020-02-26 11:38发布

问题:

This question already has answers here:
Closed 7 years ago.

Possible Duplicate:
How to prevent richTextBox to paste images within it?

If you're using Richtextbox, there are several advantages in Richtextbox for example:

we can use color font on it

Setting custom font in a region

Attach files on it.. etc

take a look at the picture:

Here is my problem:

Can i just make it text only?

In my project, attach file or the like is unnecessary at all. I even didn't want attach or paste an images on it, i just want "text only" on Richtextbox

How can i do that?

回答1:

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;
        }
    }
}


回答2:

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;
    } 
}