这是一个扩展方法,该
AppendText方法使用color参数重载该方法:
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文章。



