C # use the extended method to customize the font color of the rich text box (RichTextBox,
When developing a Winform application using C #, we may use RichTextBox to display application logs in real time. logs are classified into common messages, warning prompts, and errors. In order to better classify different types of logs, we need to use different colors to output the corresponding logs. For example, the message is generally green, the warning prompt is orange, and the error is in red.
This setting option is not available in RichTextBox of native Winform. To implement the functions described above, we can use the. NET static extension method. The classes and methods used to implement the extension method must be static. If you are not familiar with the extension method, we recommend that you first read the relevant documentation. Here I will paste the extension method to change the color of the RichTextBox Font:
using System;using System.Collections.Generic;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace DocDetector.Core.Extensions{ public static class RichTextBoxExtension { public static void AppendTextColorful(this RichTextBox rtBox, string text, Color color, bool addNewLine = true) { if (addNewLine) { text += Environment.NewLine; } rtBox.SelectionStart = rtBox.TextLength; rtBox.SelectionLength = 0; rtBox.SelectionColor = color; rtBox.AppendText(text); rtBox.SelectionColor = rtBox.ForeColor; } }}
After writing the extension method, it is very easy to use, as shown below:
rtxtLog.AppendTextColorful("Your message here",Color.Green);
Okay, you're done! Try again. Is the text output by RichTextBox green normally?
PS: if the color is red or green, you have to talk about it again. Haha ~~~
This article is published in Figure share: C # Winform custom Rich Text Box (RichTextBox) font color using the Extension Method