在格式文本框在.NET颜色文本文本框、文本、颜色、格式

2023-09-04 03:04:05 作者:我爱你与你无关

我有丰富的文本框编辑XML文本 我想如何着色在RichTextBox内部的XML标签名称是什么 我想红色或绿色的颜色标签名称。 没有办法做到这一点?

I have Rich TextBox to Edit XML Text What i want how to color the XML Tags Names inside the RichTextBox I want the tags names in RED or Green color. Any Way to do that?

推荐答案

工作什么你想要的正则表达式使用的此页面。一旦你有了这个,你可以使用类似下面的方法来更新的RichTextBox

Work out what your desired regex is using this page. Once you have this you could use something like the following method to update the RichTextBox

public static void HighlightSyntax(RichTextBox richTextBox, Regex yourRegex, Color someColor)
{
    richTextBox.BeginUpdate();
    int selPos = richTextBox.SelectionStart;
    richTextBox.SelectAll();
    richTextBox.SelectionColor = normTextColor;
    richTextBox.Select(selPos, 0);

    // For each match from the regex, highlight the word.
    foreach (Match keyWordMatch in yourRegex.Matches(richTextBox.Text))
    {
        richTextBox.Select(keyWordMatch.Index, keyWordMatch.Length);
        richTextBox.SelectionColor = someColor;
        richTextBox.Select(selPos, 0);
        richTextBox.SelectionColor = normTextColor;
    }
    richTextBox.EndUpdate();
}

您也可以通过一个定时器后自动设定时间来更新这个。

You could also adopt a timer to update this automatically after a set time.

我希望这有助于。

请注意。对于大的文本文件,而像这样的做法将是缓慢的!在这种情况下,我会采取Sinctilla.NET为如下...

Note. For large text files, and approach like this will be slow! In this case I would adopt Sinctilla.NET as a full syntax highlighter as stated in one of the answers below...