关于richtextbox改变字体颜色,加下划线
参考了三份有用的资料:
1.关于richtextbox设置字体颜色的问题
http://biancheng.dnbcw.net/c/180381.html
2.C#Winform使用扩展方法自定义富文本框(RichTextBox)字体颜色
3.RichTextBox.SelectionLength 属性
用的时候都不是一帆风顺的,别人的:
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;
}
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;//恢复默认字体,否则会影响到后面
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于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保姆级教程