在某些情况下而不是在其他情况下应用SelectionColor

时间:2019-07-11 18:51:59

标签: c# winforms

我有以下方法,应该突出显示富文本框中的某些文本行,同时还用包含注释(错误/成功)的新行替换现有行。

此方法适用于一个文件,适用于2个文件,但超出此范围的结果将导致某些中间字符串无法正确获得颜色。我是C#的新手,不确定我是否缺少某些细微差别。

希望以下内容足以为您提供帮助,但是从本质上讲,UI中的结果是第一个文件为绿色,尽管有错误,第二个文件为绿色,并且日志显示该文件应为红色,而最后一个文件正确显示为红色。

代码如下:

private void updateFileList(string fileName, string newFileName, Color color)
    {

        string matchString = Regex.Escape(fileName);
        Console.WriteLine(matchString);
        Console.WriteLine(color);
        foreach (Match match in Regex.Matches(tbFileList.Text, matchString))
        {
            Console.WriteLine("MATCH: " + match);
            tbFileList.Text = tbFileList.Text.Replace(fileName, newFileName);
            tbFileList.SelectionStart = match.Index;
            Console.WriteLine("INDEX: " + match.Index.ToString());
            tbFileList.SelectionLength = newFileName.Length;
            Console.WriteLine("LENGTH: " + newFileName.Length.ToString());
            Console.WriteLine("SELECTED TEXT: " + tbFileList.SelectedText);
            tbFileList.SelectionColor = color;
            Console.WriteLine("SELECTION COLOR: " + tbFileList.SelectionColor);

        };
    }

这是Console.WriteLine语句的结果:

===================
A:\\FileName1\.txt
Color [Green]
MATCH: A:\FileName1.txt
INDEX: 0
LENGTH: 102
SELECTED TEXT: A:\FileName1.txt | Success!
SELECTION COLOR: Color [Green]
===================
A:\\FileName2\.txt
Color [Red]
MATCH: A:\FileName2.txt
INDEX: 103
LENGTH: 164
SELECTED TEXT: A:\FileName2.txt | ERROR.
SELECTION COLOR: Color [Red]
===================
A:\\Filename3\.txt
Color [Red]
MATCH: A:\Filename3.txt
INDEX: 268
LENGTH: 147
SELECTED TEXT: A:\Filename3.txt | ERROR.
SELECTION COLOR: Color [Red]

注意

我已经更改了文件名,因此如果您将索引/长度与文件名进行比较,则可能没有意义。不过,它们似乎按顺序排列,因此,我可以肯定,它并没有抓住文本或其他内容的错误部分。

这样调用上述方法:

updateFileList(fileName, newFileName, Color.Red);

编辑

改为此更改,没有更改:

string newText = tbFileList.Text.Replace(fileName, newFileName);
tbFileList.Text = newText;

编辑2

我也尝试过:

string newText = tbFileList.Text;
tbFileList.Text = newText.Replace(fileName, newFileName);

0 个答案:

没有答案