开发语言:C#
源码大小:88KB
源码大小:88KB
/// <summary>
/// 给RichTextBox指定行设置文字颜色和字体
/// </summary>
/// <param name="rtb">目标RichTextBox控件</param>
/// <param name="lineIndex">行号(从0开始计数)</param>
/// <param name="color">要设置的颜色</param>
/// <param name="font">要设置的字体</param>
public void SetRichTextBoxLineStype(RichTextBox rtb, int lineIndex, Color color = default(Color), Font font = null)
{
// 边界校验:行号超出范围则直接返回
if (rtb.Lines.Length == 0 || lineIndex < 0 || lineIndex >= rtb.Lines.Length)
{
return;
}
// 1. 获取指定行的第一个字符索引
int lineStart = rtb.GetFirstCharIndexFromLine(lineIndex);
// 2. 计算指定行的最后一个字符索引
int lineEnd;
if (lineIndex == rtb.Lines.Length - 1)
{
// 如果是最后一行,结束位置为文本末尾
lineEnd = rtb.Text.Length;
}
else
{
// 非最后一行,结束位置为下一行首字符索引 - 1
lineEnd = rtb.GetFirstCharIndexFromLine(lineIndex + 1) - 1;
}
// 3. 选中当前行的文本(仅后台选中,界面无视觉选中效果)
rtb.SelectionStart = lineStart;
rtb.SelectionLength = lineEnd - lineStart + 1;
// 4. 设置选中区域的文字颜色和样式
if (color != default(Color))
{
rtb.SelectionColor = color;
}
if (font != null)
{
rtb.SelectionFont = font;
}
// 5. 取消选中(将光标移到文本末尾,避免界面显示选中状态)
rtb.SelectionStart = rtb.Text.Length;
rtb.SelectionLength = 0;
}
/// <summary>
/// 给RichTextBox追加文字并设置文字颜色和字体
/// </summary>
/// <param name="rtb"></param>
/// <param name="str">w追加的文字</param>
/// <param name="color">要设置的颜色</param>
/// <param name="font">要设置的字体</param>
public void RichTextAppendText(RichTextBox rtb, string str, Color color = default(Color), Font font = null)
{
if (string.IsNullOrEmpty(str?.Trim())) { return; }
rtb.SelectionStart = rtb.Text.Length;
rtb.SelectionLength = str.Length;
if (color != default(Color))
{
rtb.SelectionColor = color;
}
if (font != null)
{
rtb.SelectionFont = font;
}
rtb.AppendText(str);
rtb.SelectionStart = rtb.Text.Length;
rtb.SelectionLength = 0;
}
方法调用
SetRichTextBoxLineStype(richTextBox1, 0, Color.Red, new Font("微软雅黑", 12)); // 第0行(第一行)红色 微软雅黑 12 号字体
RichTextAppendText(richTextBox1, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}追加的文字\r\n", Color.Blue, new Font("微软雅黑", 16));// 追加的文字 蓝色 微软雅黑 16 号字体
从方法中可以看出,同一行也可以设置多个颜色,只要设置选中开始到尾的文字,方法如下
//选中当前行的文本(仅后台选中,界面无视觉选中效果) rtb.SelectionStart = lineStart; rtb.SelectionLength = lineEnd - lineStart + 1; //设置选中区域的文字颜色 rtb.SelectionColor = color;
视频讲解,点击进入B站可看高清视频
本文来自 www.luofenming.com