I am doing an app that adds a certain character for each selected line if you click the button. for example \"//\" in each line in a Richtextbox and colored the text into re
Manipulating a RichTextBox
correctly is a little more involved than changing the Text
. Here is a code example that will help you.
Note that is never changes the Text
directly, so it won't mess up the previous formatting and that it tries to restore the selection.
It allows you to comment out several sections independently. It takes the comment string from a TextBox
for testing and it restores to Black
..
// get all line numbers that belong to the selection
List getSelectedLines(RichTextBox RTB)
{
List lines = new List();
int sStart = RTB.SelectionStart;
int sEnd = RTB.SelectionLength + sStart;
int line1 = RTB.GetLineFromCharIndex(sStart);
int line2 = RTB.GetLineFromCharIndex(sEnd);
for (int l = line1; l <= line2; l++) lines.Add(l);
return lines;
}
// prefix a line with a string
void prependLine(RichTextBox RTB, int line, string s)
{
int sStart = RTB.SelectionStart;
int sLength = RTB.SelectionLength;
RTB.SelectionStart = RTB.GetFirstCharIndexFromLine(line);
RTB.SelectionLength = 0;
RTB.SelectedText = s;
RTB.SelectionStart = sStart;
RTB.SelectionLength = sLength;
}
// color one whole line
void colorLine(RichTextBox RTB, int line, Color c)
{
int sStart = RTB.SelectionStart;
int sLength = RTB.SelectionLength;
RTB.SelectionStart = RTB.GetFirstCharIndexFromLine(line);
RTB.SelectionLength = RTB.Lines[line].Length; ;
RTB.SelectionColor = c;
RTB.SelectionStart = sStart;
RTB.SelectionLength = sLength;
}
// additional function, may come handy..
void trimLeftLine(RichTextBox RTB, int line, int length)
{
int sStart = RTB.SelectionStart;
int sLength = RTB.SelectionLength;
RTB.SelectionStart = RTB.GetFirstCharIndexFromLine(line);
RTB.SelectionLength = length;
RTB.Cut();
RTB.SelectionStart = sStart;
RTB.SelectionLength = 0;
}
// remove a string token from the start of a line
void trimLeftLine(RichTextBox RTB, int line, string token)
{
int sStart = RTB.SelectionStart;
int sLength = RTB.SelectionLength;
RTB.SelectionStart = RTB.GetFirstCharIndexFromLine(line);
RTB.SelectionLength = token.Length;
if (RTB.SelectedText == token) RTB.Cut();
RTB.SelectionStart = sStart;
RTB.SelectionLength = 0;
}
This is the comment button:
private void button1_Click(object sender, EventArgs e)
{
List lines = getSelectedLines(richTextBox1);
foreach (int l in lines) prependLine(richTextBox1, l, tb_comment.Text);
foreach (int l in lines) colorLine(richTextBox1, l, Color.Firebrick);
}
This is the uncomment button:
private void button2_Click(object sender, EventArgs e)
{
List lines = getSelectedLines(richTextBox1);
foreach (int l in lines) trimLeftLine(richTextBox1, l, tb_comment.Text);
foreach (int l in lines) colorLine(richTextBox1, l, Color.Black);
}