RichTextBox中的颜色​​特定行

时间:2016-06-01 21:23:41

标签: c# wpf richtextbox

我的应用程序中有一个RichTextBox,它读取一个文本文件,一个完全正确的日志文件,如下所示: http://pastebin.com/3ETeYSUH 接下来就是这样。

我的问题是,我怎样才能将整条线染成“Sikertelencsatlakozás”的RED? (是的,匈牙利语,意思是:“无法连接”)

我的代码读取文件:

string fileName = "servermanagerlog.txt";
            TextRange range;
            FileStream fStream;
            if (File.Exists(fileName))
            {
                range = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
                fStream = new FileStream(fileName, FileMode.OpenOrCreate);
                range.Load(fStream, DataFormats.Text);
                fStream.Close();
            }
            richTextBox.ScrollToEnd();

1 个答案:

答案 0 :(得分:0)

尝试此代码(我只是手动添加文本而不是文件):

    void richTextBox_Loaded(object sender, RoutedEventArgs e)
    {
        TextRange range = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
        range.Text = "Here is one line with some text" + Environment.NewLine;
        range.Text += "Here is another line Sikertelen csatlakozás with some text" + Environment.NewLine;
        range.Text += "Here is another line with some text" + Environment.NewLine;
        range.Text += "Here is another line Sikertelen csatlakozás with some text" + Environment.NewLine;
        range.Text += "Here is one line with some text" + Environment.NewLine;
        range.Text += "Here is another line Sikertelen csatlakozás with some text" + Environment.NewLine;
        range.Text += "Here is another line with some text" + Environment.NewLine;
        range.Text += "Here is another line Sikertelen csatlakozás with some text" + Environment.NewLine;

        String strSearch = "Sikertelen csatlakozás";
        int start = range.Text.IndexOf(strSearch);

        TextPointer tp = null;

        if (start > -1)
        {
            tp = range.Start.GetPositionAtOffset(start);
        }

        while (tp != null)
        {
            TextPointer tpLine = tp.GetLineStartPosition(0);

            TextPointer tpLineEnd = tp.GetLineStartPosition(1);
            TextPointer lineEnd = (tpLineEnd !=null ? tpLineEnd : tp.DocumentEnd).GetInsertionPosition(LogicalDirection.Backward);

            TextRange redText = new TextRange(tpLine, lineEnd);
            redText.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
            tp = tpLineEnd;

            if (tp != null)
            {
                start = range.Text.IndexOf(strSearch, start + 1);

                if (start > -1)
                {
                    tp = range.Start.GetPositionAtOffset(start);
                }
            }
        }
    }

我使用以下Stack Overflow链接获取有关查找文本的详细信息:WPF Richtextbox Application.Find Text spanning Multiple runs,获取行:Using GetLineStartPosition to get the end of a line in WPF RichTextBox并最终为文本着色:Change color and font for some part of text in WPF C#

相关问题