欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# Winform使用扩展方法实现自定义富文本框(RichTextBox)字体颜色

程序员文章站 2023-12-01 17:05:40
在利用c#开发winform应用程序的时候,我们有可能使用richtextbox来实现实时显示应用程序日志的功能,日志又分为:一般消息,警告提示和错误等类别。为了更好地区分...

在利用c#开发winform应用程序的时候,我们有可能使用richtextbox来实现实时显示应用程序日志的功能,日志又分为:一般消息,警告提示和错误等类别。为了更好地区分不同类型的日志,我们需要使用不同的颜色来输出对应的日志,比如:一般消息为绿色,警告提示的用橙色,错误的用红色字体。

在原生winform的richtextbox中,是没有这种设置选项的。如需实现以上描述的功能,我们可以使用.net的静态扩展方法来处理。实现扩展方法的类和方法本身都必须是静态的,如果你对扩展方法还不是太了解,建议先查阅相关文档资料。我这里就把实现改变richtextbox字体颜色的扩展方法贴出:

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;
  }
 }
}

写好扩展方法后,使用就非常简单了,如下:

rtxtlog.appendtextcolorful("your message here",color.green);

好了,大功告成!试一下,正常的看到的richtextbox输出的文字是否是绿色的呢?
ps:如果是红绿色盲就得另说了,哈哈~~~

希望本文所述对大家的winform程序设计有所帮助。