一个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点23分]网友:我在这里的消息
[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();
请注意,如果你输了很多的消息,你可能会注意到一些闪烁。见<一href=\"http://www.c-sharpcorner.com/UploadFile/mgold/ColorSyntaxEditor12012005235814PM/ColorSyntaxEditor.aspx\">this C#角的文章,就如何减少RichTextBox的闪烁的想法。
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屋!