有选择地为 RichTextBox 中的文本着色

发布于 2024-07-11 17:31:27 字数 38 浏览 6 评论 0原文

如何在RichTextBox中每次遇到字母“A”时就涂成红色?

How can I paint in red every time I meet the letter "A" in RichTextBox?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

黯淡〆 2024-07-18 17:31:27

尝试这个:

static void HighlightPhrase(RichTextBox box, string phrase, Color color) {
  int pos = box.SelectionStart;
  string s = box.Text;
  for (int ix = 0; ; ) {
    int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase);
    if (jx < 0) break;
    box.SelectionStart = jx;
    box.SelectionLength = phrase.Length;
    box.SelectionColor = color;
    ix = jx + 1;
  }
  box.SelectionStart = pos;
  box.SelectionLength = 0;
}

...

private void button1_Click(object sender, EventArgs e) {
  richTextBox1.Text = "Aardvarks are strange animals";
  HighlightPhrase(richTextBox1, "a", Color.Red);
}

Try this:

static void HighlightPhrase(RichTextBox box, string phrase, Color color) {
  int pos = box.SelectionStart;
  string s = box.Text;
  for (int ix = 0; ; ) {
    int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase);
    if (jx < 0) break;
    box.SelectionStart = jx;
    box.SelectionLength = phrase.Length;
    box.SelectionColor = color;
    ix = jx + 1;
  }
  box.SelectionStart = pos;
  box.SelectionLength = 0;
}

...

private void button1_Click(object sender, EventArgs e) {
  richTextBox1.Text = "Aardvarks are strange animals";
  HighlightPhrase(richTextBox1, "a", Color.Red);
}
物价感观 2024-07-18 17:31:27

下面是我的包装类中用于完成此工作的一个片段:

    private delegate void AddMessageCallback(string message, Color color);

    public void AddMessage(string message)
    {
        Color color = Color.Empty;

        string searchedString = message.ToLowerInvariant();

        if (searchedString.Contains("failed")
            || searchedString.Contains("error")
            || searchedString.Contains("warning"))
        {
            color = Color.Red;
        }
        else if (searchedString.Contains("success"))
        {
            color = Color.Green;
        }

        AddMessage(message, color);
    }

    public void AddMessage(string message, Color color)
    {
        if (_richTextBox.InvokeRequired)
        {
            AddMessageCallback cb = new AddMessageCallback(AddMessageInternal);
            _richTextBox.BeginInvoke(cb, message, color);
        }
        else
        {
            AddMessageInternal(message, color);
        }
    }

    private void AddMessageInternal(string message, Color color)
    {
        string formattedMessage = String.Format("{0:G}   {1}{2}", DateTime.Now, message, Environment.NewLine);

        if (color != Color.Empty)
        {
            _richTextBox.SelectionColor = color;
        }
        _richTextBox.SelectedText = formattedMessage;

        _richTextBox.SelectionStart = _richTextBox.Text.Length;
        _richTextBox.ScrollToCaret();
    }

现在您可以使用 AddMessage("The command failed") 来调用它,以使其自动以红色突出显示。 或者您可以使用 AddMessage("Just aspecial message", Color.Purple) 调用它来定义特殊颜色(例如,在 catch 块中定义特定颜色很有帮助,无论消息内容如何)

Here is a snippet out of my wrapper class to do this job:

    private delegate void AddMessageCallback(string message, Color color);

    public void AddMessage(string message)
    {
        Color color = Color.Empty;

        string searchedString = message.ToLowerInvariant();

        if (searchedString.Contains("failed")
            || searchedString.Contains("error")
            || searchedString.Contains("warning"))
        {
            color = Color.Red;
        }
        else if (searchedString.Contains("success"))
        {
            color = Color.Green;
        }

        AddMessage(message, color);
    }

    public void AddMessage(string message, Color color)
    {
        if (_richTextBox.InvokeRequired)
        {
            AddMessageCallback cb = new AddMessageCallback(AddMessageInternal);
            _richTextBox.BeginInvoke(cb, message, color);
        }
        else
        {
            AddMessageInternal(message, color);
        }
    }

    private void AddMessageInternal(string message, Color color)
    {
        string formattedMessage = String.Format("{0:G}   {1}{2}", DateTime.Now, message, Environment.NewLine);

        if (color != Color.Empty)
        {
            _richTextBox.SelectionColor = color;
        }
        _richTextBox.SelectedText = formattedMessage;

        _richTextBox.SelectionStart = _richTextBox.Text.Length;
        _richTextBox.ScrollToCaret();
    }

Now you can call it with AddMessage("The command failed") to get it automatically highlight in red. Or you can call it with AddMessage("Just a special message", Color.Purple) to define a special color (Helpful e.g. within catch blocks to define a specific color, regardless of the message content)

撑一把青伞 2024-07-18 17:31:27

如果这就是您正在寻找的内容,那么在您打字时这将不起作用,但我用它来突出显示子字符串:

Function Highlight(ByVal Search_Str As Object, ByVal InputTxt As String, ByVal StartTag As String, ByVal EndTag As String) As String
    Highlight = Regex.Replace(InputTxt, "(" & Regex.Escape(Search_Str) & ")", StartTag & "$1" & EndTag, RegexOptions.IgnoreCase)
End Function

并以这种方式调用它:

Highlight("A", "Color All my A's red", [span class=highlight]', '[/span]')

其中“突出显示”类具有您想要的任何颜色编码/格式:顺便

.highlight {text-decoration: none;color:black;background:red;}

说一句:您需要将这些方括号更改为有角度的方括号...当我输入它们时它们不会出现...

This won't work while you are typing if that is what you are looking for, but I use this to highlight substrings:

Function Highlight(ByVal Search_Str As Object, ByVal InputTxt As String, ByVal StartTag As String, ByVal EndTag As String) As String
    Highlight = Regex.Replace(InputTxt, "(" & Regex.Escape(Search_Str) & ")", StartTag & "$1" & EndTag, RegexOptions.IgnoreCase)
End Function

and call it this way:

Highlight("A", "Color All my A's red", [span class=highlight]', '[/span]')

Where the class 'highlight' has whatever color coding/formatting you want:

.highlight {text-decoration: none;color:black;background:red;}

BTW: you need to change those square brackets to angled ones...they wouldn't come thru when I typed them...

风轻花落早 2024-07-18 17:31:27

这是 EJ Brennan 答案的 C# 代码:

public string Highlight(object Search_Str, string InputTxt, string StartTag, string EndTag) 
{
    return Regex.Replace(InputTxt, "(" + Regex.Escape(Search_Str) + ")", StartTag + "$1" + EndTag, RegexOptions.IgnoreCase);
}

This is the C# code for EJ Brennan's answer:

public string Highlight(object Search_Str, string InputTxt, string StartTag, string EndTag) 
{
    return Regex.Replace(InputTxt, "(" + Regex.Escape(Search_Str) + ")", StartTag + "$1" + EndTag, RegexOptions.IgnoreCase);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文