关于richtextbox改变字体颜色,加下划线

参考了三份有用的资料:

1.关于richtextbox设置字体颜色的问题

http://biancheng.dnbcw.net/c/180381.html

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

http://www.cnblogs.com/bobositlife/p/csharp-winform-change-richtextbox-font-color-using-static-extension-method.html

3.RichTextBox.SelectionLength 属性

https://msdn.microsoft.com/zh-cn/library/windows/desktop/system.windows.forms.richtextbox.selectionlength(v=vs.100).aspx/html

  用的时候都不是一帆风顺的,别人的:

  1.

private void AddTextAndSetFonts(RichTextBox rtx, string addStr, Color textColor)
{
int start = rtx.Text.Length;
int length = addStr.Length;
rtx.AppendText(addStr);
rtx.SelectionStart = start;
rtx.SelectionLength = length;
rtx.SelectionColor = textColor;
}
2.

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;
    }
 
3
private void ModifySelectedText()
{
   // Determine if text is selected in the control.
   if (richTextBox1.SelectionLength > 0)
   {
      // Set the color of the selected text in the control.
      richTextBox1.SelectionColor = Color.Red;
      // Set the font of the selected text to bold and underlined.
      richTextBox1.SelectionFont = new Font("Arial",10,FontStyle.Bold | FontStyle.Underline);
      // Protect the selected text from modification.
      richTextBox1.SelectionProtected = true;
   }
}

 尤其要注意代码顺序不然会有问题,还有就是设置后要取消。经过自己改造后的

private void AppendTextUnderline(RichTextBoxEx rtBox, string text, Color color, bool addNewLine)
{
if (addNewLine)
{
text += Environment.NewLine;
}
// int start = rtBox.Text.Length;
// int text_length = text.Length;

rtBox.SelectionStart = rtBox.Text.Length;
//rtBox.SelectionLength = text_length;
rtBox.SelectionColor = color;
rtBox.SelectionFont = new Font("Arial", 10, FontStyle.Bold | FontStyle.Underline);
rtBox.AppendText(text);
rtBox.SelectionColor = rtBox.ForeColor;
rtBox.SelectionFont = rtBox.Font;//恢复默认字体,否则会影响到后面
}

 

 

posted @   Youse的二分口粮地  阅读(629)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程
点击右上角即可分享
微信分享提示