C# RichTextBox颜色特定行
如何给RichTextBox中以#开头的行上色,就像python中的注释一样。我有这个代码,但它应该只给其中的行上色。我的代码在编写完一个#后为所有内容着色:C# RichTextBox颜色特定行,c#,winforms,C#,Winforms,如何给RichTextBox中以#开头的行上色,就像python中的注释一样。我有这个代码,但它应该只给其中的行上色。我的代码在编写完一个#后为所有内容着色: private void richTextBox1_TextChanged(object sender, EventArgs e) { string text = richTextBox1.Text; if (richTextBox1.Lines.Contains("#") == true) { int firstch
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
string text = richTextBox1.Text;
if (richTextBox1.Lines.Contains("#") == true)
{
int firstcharindex = richTextBox1.GetFirstCharIndexOfCurrentLine();
int currentline = richTextBox1.GetLineFromCharIndex(firstcharindex);
richTextBox1.Select(firstcharindex, 10);
richTextBox1.SelectionColor = Color.Red;
richTextBox1.DeselectAll();
richTextBox1.Select(richTextBox1.Text.Length, 0);
}
}
您必须指定
richTextBox1.SelectionLength
。您必须将其设置为您的行长度
另请参见:如果缺少else条件,请对TexBox中的每一行执行此操作,如下所示
string text = richTextBox1.Text;
foreach (var line in richTextBox1.Lines)
{
if (line.Contains("#"))
{
int firstcharindex = richTextBox1.GetFirstCharIndexOfCurrentLine();
int currentline = richTextBox1.GetLineFromCharIndex(firstcharindex);
richTextBox1.Select(firstcharindex, 10);
richTextBox1.SelectionColor = Color.Red;
richTextBox1.DeselectAll();
richTextBox1.Select(richTextBox1.Text.Length, 0);
}
else
{
int firstcharindex = richTextBox1.GetFirstCharIndexOfCurrentLine();
int currentline = richTextBox1.GetLineFromCharIndex(firstcharindex);
richTextBox1.Select(firstcharindex, 10);
richTextBox1.SelectionColor = Color.Black;
richTextBox1.DeselectAll();
richTextBox1.Select(richTextBox1.Text.Length, 0);
}
}
很高兴这有帮助you@gabrielgoller请像回答一样标记它。