【问题标题】:RichTextBox Select + SelectionColor does not workRichTextBox Select + SelectionColor 不起作用
【发布时间】:2020-10-14 01:28:30
【问题描述】:

我试图通过将我的代码放在 RichTextBox_TextChanged 事件处理程序中来突出显示我正在输入的代码。

我的问题是代码选择了,但它是蓝色背景和白色文本的正常选择,就像你用鼠标一样。

如果我然后尝试输入一些内容,它会输入我想要的颜色,并且之前的选择保持不变。这一切都只是一团糟。

我的代码:

    string hello = "World";
    int index = RTB.Text.IndexOf(hello);
    int length = hello.Length;

    if (-1 != index)
    {
        RTB1.Select(index, length);
        RTB1.SelectionColor = Color.Red;
    }

在 C# 中实现快速语法高亮的正确方法是什么?

还有什么比使用 RichTextBox 选择更好的吗?一些控件允许您更改文本位的颜色而无需选择它们并更改选择的颜色?我想这样会更快更方便。

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    存储当前选定的文本开始/长度,以便您可以将其恢复为更改文本颜色之前的状态。比如:

    string hello = "World";
    int start = RTB1.SelectionStart;
    int length = RTB1.SelectionLength;
    if (RTB1.Find(hello) != -1) // selects it for you
    {
        RTB1.SelectionColor = Color.Red;
        RTB1.Select(start, length); // put selection back to the way it was
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-13
      • 2017-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多