Hi foxhunt99,
As you have seen, once a new line is inserted into the RichTextBox. The RichTextBox.SelectionStart and SelectionLength properties are set to Zero. You need to manually reselect the “Error Text�and reset their color. This is not a convenient way, but it works. If anyone else has a better approach, please share it with us.
In the following code sample, RichTextBox1_TextChanged event handler is used to monitor the change of the text and reselect the “Error Text�
Code Snippet
partial class Form1 : Form
private void Form1_Load(object sender, EventArgs e)
{
richTextBox1.Text += "#1 adfadf" + "\r\n";
richTextBox1.Text += "#2 index1, index2" + "\r\n";
richTextBox1.Text += "#3 adsfasdf" + "\r\n";
richTextBox1.Text += "#4 adsfasdf" + "\r\n";
SelectErrorText();
}
private void SelectErrorText()
{
int oldSelectionStartIndex = richTextBox1.SelectionStart;
int oldSelectionLength = richTextBox1.SelectionLength;
int secondLine = richTextBox1.GetFirstCharIndexFromLine(1);
int thirdLine = richTextBox1.GetFirstCharIndexFromLine(2);
richTextBox1.SelectionStart = secondLine;
richTextBox1.SelectionLength = thirdLine - secondLine;
richTextBox1.SelectionColor = Color.Red;
richTextBox1.Select(oldSelectionStartIndex, oldSelectionLength);
}
private void insertNewLineButton_Click(object sender, EventArgs e)
{
richTextBox1.Text += "A New Line" + "\r\n";
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
if (richTextBox1.TextLength >= 30)
{
SelectErrorText();
}
}
Best regards,
Jacob
|