关于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;//恢复默认字体,否则会影响到后面
}

 

 

悲观者更正确,乐观者更成长。时代大潮下,充满着机遇和风险。 目标不同,选择也就不同,人生没有标准答案,对大多数人而言,还是要不停地提高自己,这个世界什么都能快,但学习从来都没有捷径,或者说学习已是捷径。
原文地址:https://www.cnblogs.com/youzi-xuchongyou/p/8862621.html