颜色RichTextBox字符串的不同部分 [英] Color different parts of a RichTextBox string

查看:230
本文介绍了颜色RichTextBox字符串的不同部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图着色一个字符串的部分,以附加到RichTextBox。我有一个从不同的字符串构建的字符串。

I'm trying to color parts of a string to be appended to a RichTextBox. I have a string built from different strings.

string temp = "[" + DateTime.Now.ToShortTimeString() + "] " +
              userid + " " + message + Environment.NewLine;

这是邮件构造后的外观。

This is what the message would look like once it is constructed.


[9:23 pm]用户:我的邮件在这里。

[9:23pm] User: my message here.

包括括号[9:23]中的一切都是一种颜色,用户是另一种颜色,消息是另一种颜色。

I want everything within and including the brackets [9:23] to be one color, 'user' to be another color and the message to be another color. Then I'd like the string appended to my RichTextBox.

如何做到这一点?

推荐答案

这里是一个扩展方法,使用颜色参数重载 AppendText 方法:

Here is an extension method that overloads the AppendText method with a color parameter:

public static class RichTextBoxExtensions
{
    public static void AppendText(this RichTextBox box, string text, Color color)
    {
        box.SelectionStart = box.TextLength;
        box.SelectionLength = 0;

        box.SelectionColor = color;
        box.AppendText(text);
        box.SelectionColor = box.ForeColor;
    }
}

这是你将如何使用它:

var userid = "USER0001";
var message = "Access denied";
var box = new RichTextBox
              {
                  Dock = DockStyle.Fill,
                  Font = new Font("Courier New", 10)
              };

box.AppendText("[" + DateTime.Now.ToShortTimeString() + "]", Color.Red);
box.AppendText(" ");
box.AppendText(userid, Color.Green);
box.AppendText(": ");
box.AppendText(message, Color.Blue);
box.AppendText(Environment.NewLine);

new Form {Controls = {box}}.ShowDialog();

请注意,如果输出大量邮件,您可能会注意到闪烁。有关如何减少RichTextBox的想法,请参见此C#Corner 文章闪烁。

Note that you may notice some flickering if you're outputting a lot of messages. See this C# Corner article for ideas on how to reduce RichTextBox flicker.

这篇关于颜色RichTextBox字符串的不同部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆