正确操作RichTextBox比更改Text要复杂一些。这是一个可以帮助您的代码示例。
请注意,它永远不会直接更改 Text,因此它不会弄乱以前的格式,并且它会尝试恢复选择。
它允许您独立注释掉几个部分。它从TextBox 获取注释字符串进行测试,然后恢复为Black..
// get all line numbers that belong to the selection
List<int> getSelectedLines(RichTextBox RTB)
{
List<int> lines = new List<int>();
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;
}
这是评论按钮:
private void button1_Click(object sender, EventArgs e)
{
List<int> lines = getSelectedLines(richTextBox1);
foreach (int l in lines) prependLine(richTextBox1, l, tb_comment.Text);
foreach (int l in lines) colorLine(richTextBox1, l, Color.Firebrick);
}
这是取消注释按钮:
private void button2_Click(object sender, EventArgs e)
{
List<int> lines = getSelectedLines(richTextBox1);
foreach (int l in lines) trimLeftLine(richTextBox1, l, tb_comment.Text);
foreach (int l in lines) colorLine(richTextBox1, l, Color.Black);
}