问题
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