c# - .NET 富文本框中的彩色文本

标签 c# .net vb.net

我有 Rich TextBox 来编辑 XML 文本 我想要如何为 RichTextBox 内的 XML 标签名称着色
我想要红色或绿色的标签名称。
有办法做到这一点吗?

最佳答案

找出您想要的正则表达式正在使用this page 。一旦你有了这个,你可以使用类似下面的方法来更新 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();
}

您还可以采用计时器在设定时间后自动更新。

我希望这会有所帮助。

注意。对于大文本文件,这样的方法会很慢!在这种情况下,我将采用 Sinctilla.NET 作为完整的语法荧光笔,如下面的答案之一所述......

关于c# - .NET 富文本框中的彩色文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13007560/

相关文章:

c# - UWP 导航查看同一类型的多个页面

c# - 单击按钮返回/获取 DataGrid 行索引

c# - 如何从 .net Core 2.2 中的 appsettings.json 读取日志配置

.net - 如何在 VB.NET 中获取 Caps Lock 的当前状态?

vb.net - 在 Visual Basic 中使用 json.net 解析嵌套 JSON

c# - 如何使用不是第二个对象的主键的键创建导航属性?

c# - 为什么我们要引用其他项目?

c# - 如何为已取消的任务添加延续

.net - 错误 : . NET Framework 4.7.2 或更高版本的更新已安装在此计算机上

mysql - 存储 pdf 文件的最佳方法是什么?