I want to insert a string in my RichTextbox, at a specific position and with a specific color. So I tried to add an extension for the method AppendText() of the RichTextbox class.
public static void AppendText(this RichTextBox Box, string Text, Color col, int SelectionStart)
{
Box.SelectionStart = SelectionStart;
Box.SelectionLength = 0;
Box.SelectionColor = col;
Box.SelectionBackColor = col;
Box.Text = Box.Text.Insert(SelectionStart, Text);
Box.SelectionColor = Box.ForeColor;
}
I tried to use this in a class called RichTextBoxExtension. The result is not as per my expectation. The string is inserted but not with the color selected.
Is there any better way to do this functionality?
EDIT: I think it could be interesting to inform you why I need this functionality. Actually, when user write a closing parenthesis, I would like to highligh (or color) the associative opening parenthesis. so for example if the user write (Mytext), the first parenthesis will be in color when user tapped ")" and keep the selection on this parenthesis.
You have to use the SelectedText property of the RichTextBox control. Also make sure to keep track of the values of the current selection before you change anything.
Your code should look like this (I give away what Hans was hinting at) :
public static void AppendText(this RichTextBox Box,
string Text,
Color col,
int SelectionStart)
{
// keep all values that will change
var oldStart = Box.SelectionStart;
var oldLen = Box.SelectionLength;
//
Box.SelectionStart = SelectionStart;
Box.SelectionLength = 0;
Box.SelectionColor = col;
// Or do you want to "hide" the text? White on White?
// Box.SelectionBackColor = col;
// set the selection to the text to be inserted
Box.SelectedText = Text;
// restore the values
// make sure to correct the start if the text
// is inserted before the oldStart
Box.SelectionStart = oldStart < SelectionStart ? oldStart : oldStart + Text.Length;
// overlap?
var oldEnd = oldStart + oldLen;
var selEnd = SelectionStart + Text.Length;
Box.SelectionLength = (oldStart < SelectionStart && oldEnd > selEnd) ? oldLen + Text.Length : oldLen;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With