为 RichTextBox 字符串的不同部分着色 [英] Color different parts of a RichTextBox string
问题描述
我正在尝试为要附加到 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:23pm] 用户:我的消息在这里.
[9:23pm] User: my message here.
我希望括号 [9:23] 内和包括括号内的所有内容都为一种颜色,用户"为另一种颜色,而消息为另一种颜色.然后我想将字符串附加到我的 RichTextBox.
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.
我怎样才能做到这一点?
How can I accomplish this?
推荐答案
这里有一个扩展方法,它使用颜色参数重载 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;
}
}
这就是你将如何使用它:
And this is how you would use it:
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屋!