Retain highlighted color of text after editing

喜欢而已 提交于 2021-02-05 11:52:36

问题


Cannot keep the highlighted effect I set in my RichTextBox on my text after removing content of a line in front of him.

No matter how much text I remove from the control it always removes the custom SelectionColor and SelectionBackColor I set to a text already contained in it.

Code of my Removal method:

private void btnRemove_Click(object sender, EventArgs e)
{
    //Remove selected line from RichTextBox
    richTextBox1.Text = richTextBox1.Text.Remove(richTextBox1.Text.Length - 1, 1);
    //Remove all blank lines remaining after deletion                  
    richTextBox1.Text = Regex.Replace(richTextBox1.Text, @"^\s*$(\n|\r|\r\n)", "", RegexOptions.Multiline);
}

The number of letters I want to remove here is 1 as the word "AND" is a simple image inserted by means of Clipboard Paste method.


回答1:


You must never (read my lips: Never, never, never) change to Text or the Lines property of a RichtTextBox or else you will lose/mess up all previous formatting.

So you need to change this:

richTextBox1.Text = richTextBox1.Text.Remove(richTextBox1.Text.Length - 1, 1);

To this sequence:

First Select the part of the Text you want to change in some way:

richTextBox1.SelectionStart = richTextBox1.Text.Length - 1;
richTextBox1.SelectionLength = 1;

Now you can change it. To delete either use:

richTextBox1.SelectedText = "";

or

richTextBox1.Cut(); 

The latter version also will place the text in the clipboard; doing it it will keep the formatting of that portion and you could Paste it to some other place..

The same rules apply when you want to add or change any type of formatting:

First Select Then Modify

And, yes, this means that the second command will grow quite a bit, i.e. you will have to replace the RegEx.Replace by a loop :-(



来源:https://stackoverflow.com/questions/37064223/retain-highlighted-color-of-text-after-editing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!