In the field of C# programming, it is a very practical function to enhance the visualization effect of RichTextBox by adding colored text. Let's say you crafted a string with different parts, each part should have its own unique color. The goal is to seamlessly add this multi-colored string to your RichTextBox and paint the individual elements with the specified color.
To achieve this, a clever solution emerged: an extension method called AppendText
, which adds a color parameter. This method elegantly embeds the specified text into a RichTextBox, decorated with the selected color.
<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>
With this extension method, using it is as easy as creating your masterpiece:
<code class="language-csharp">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(" "); // 以绿色打印用户ID box.AppendText(userid, Color.Green); // 添加冒号 box.AppendText(": "); // 以蓝色显示消息 box.AppendText(message, Color.Blue); // 追加换行符 box.AppendText(Environment.NewLine); // 创建窗体并显示RichTextBox new Form { Controls = { box } }.ShowDialog();</code>
This code neatly demonstrates how to append each part of a string along with its assigned color, creating a visually appealing and informative RichTextBox.
It is worth noting that if you are experiencing flickering issues when outputting large amounts of messages, the C# Corner article linked below provides valuable insight on how to mitigate this behavior:
The above is the detailed content of How to Color Different Parts of a String in a C# RichTextBox?. For more information, please follow other related articles on the PHP Chinese website!