我如何只为richTextBox中每行的数字着色?

时间:2017-07-10 20:02:31

标签: c# .net winforms

我想要做的是只用红色填充richTextBox2中的数字。 但它在richTextBox2中的整个文本中用红色着色。

public static class RichTextBoxExtensions
    {
        public static void AppendText(this RichTextBox box, string text, Color color)
        {
            box.SelectionStart = box.TextLength;
            box.SelectionLength = 0;

            box.SelectionColor = color;
            box.AppendText(text);
            box.SelectionColor = box.ForeColor;
        }
    }

在构造函数中:

string text = File.ReadAllText(@"C:\test\new 2.txt");
richTextBox1.Text = text;
string[] lines = richTextBox1.Lines;
for (int i = 0; i < lines.Length; i++)
{
    string tt = (i + 1).ToString();
    RichTextBoxExtensions.AppendText(richTextBox2, tt, Color.Red);
    lines[i] = tt + " " + lines[i];
}
richTextBox2.Lines = lines;

在尝试为数字着色之前,这是原始代码。

string[]  lines = richTextBox2.Lines;

for (int i = 0; i < lines.Length; i++)
{
    lines[i] = (i+1) + " " + lines[i];
}
richTextBox2.Lines = lines;

1 个答案:

答案 0 :(得分:1)

如果您希望扩展方法附加文本但只为数字着色,那么您只需要先添加文本,一次添加一个字符,扫描每个字符以查看它是否为数字,如果是,请选择它并着色它:

public static class Extenstions
{
    public static void AppendText(this RichTextBox box, string text, Color color)
    {
        // Append the text, but color only the numbers
        foreach (char character in text)
        {
            box.AppendText(character.ToString());

            if (char.IsNumber(character))
            {
                box.SelectionStart = box.TextLength - 1;
                box.SelectionLength = 1;
                box.SelectionColor = color;
                box.SelectionStart = box.TextLength;
                box.SelectionColor = box.ForeColor;
            }
        }
    }
}