When developing Winform applications using C#, we may use RichTextBox to realize the function of displaying application logs in real time. The logs are divided into categories such as general messages, warning prompts and errors. In order to better distinguish different types of logs, we need to use different colors to output the corresponding logs, such as: the general message is green, the warning prompts are orange, and the wrong font is red.
There is no such setting option in RichTextBox of native Winform. To implement the functions described above, we can use .NET's static extension method to handle it. The classes and methods that implement extension methods must be static themselves. If you don’t know much about extension methods, it is recommended to consult the relevant documents first. Here I will post the extension method to change the font color of RichTextBox:
using System; using ; using ; using ; using ; using ; using ; namespace { public static class RichTextBoxExtension { public static void AppendTextColorful(this RichTextBox rtBox, string text, Color color, bool addNewLine = true) { if (addNewLine) { text += ; } = ; = 0; = color; (text); = ; } } }
After writing the extension method, it is very simple to use, as follows:
("Your message here",);
OK, the job is done! Try it, are the text output of RichTextBox that you see normally is green?
PS: If it is red and green blind, it has to be said differently, haha~~~
I hope this article will be helpful to everyone's WinForm programming.