The text display in the RichTextBox control usually needs to use different colors to highlight the specific part. Consider such a scenario: You have a dynamic string, which contains different content. In this case, you may want to allocate different colors for the timestamp, username and message itself.
In order to achieve this coloring, a expansion method can be achieved to re -load the APPENDTEXT method of Richtextbox and add a color parameter:
Using this expansion method, you can color the various parts of the string shown below:
<code class="language-C#">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>
This technology provides precise control of the color coloring of Richtextbox content, which enhances its visual attractiveness and readability.
<code class="language-C#">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>
The above is the detailed content of How Can I Colorize Different Segments of Text within a RichTextBox?. For more information, please follow other related articles on the PHP Chinese website!