Colorize different parts of RichTextBox append text in C#
Question:
You want to selectively color certain parts of the string attached to the RichTextBox. Specifically, you want the bracketed text, the user information, and the actual message to be drawn in different colors.
Solution: Extension method with color parameter
To achieve your goals, you can use an extension method to overload the AppendText method and introduce a color parameter. Here is the code:
<code class="language-csharp">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; //重置颜色 } }</code>
Usage:
After defining the extension method, it is very simple to use. Just use it as shown in the following code:
<code class="language-csharp">string userid = "USER0001"; string message = "访问被拒绝"; RichTextBox 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); Form form = new Form { Controls = { box } }; form.ShowDialog();</code>
Note:
Please note that excessive text output may cause the RichTextBox to flicker. Please refer to the C# Corner article mentioned in the answer for possible solutions.
The above is the detailed content of How Can I Color Different Parts of Text Appended to a RichTextBox in C#?. For more information, please follow other related articles on the PHP Chinese website!