You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Winform中如何为RichTextBox选中文本前后插入指定HTML标签

C# Winform RichTextBox 选中内容加标签实现方案

原使用全局Replace()方法的问题为:该方法会匹配全文所有和选中内容相同的字符串进行替换,没有利用选中区域的位置信息,无法实现仅修改目标选中内容的需求。

推荐最简实现方案

直接修改RichTextBox的SelectedText属性即可,该属性赋值时会直接替换当前选中的区域内容,不会影响其他位置的文本:

// 先判断是否存在选中内容,避免插入空标签
if (richTextBox1.SelectionLength > 0)
{
    richTextBox1.SelectedText = $"<red>{richTextBox1.SelectedText}</red>";
}

该方案为控件原生支持,性能更高,不会触发整个文本框重绘导致闪屏,赋值后光标会自动定位到插入内容的末尾,符合编辑器常规操作逻辑。

手动拼接实现方案(适用于需要额外处理全量文本的场景)

如果需要对全量文本做自定义逻辑处理,可以通过选中区域的起始位置和长度手动拼接字符串:

if (richTextBox1.SelectionLength > 0)
{
    string fullText = richTextBox1.Text;
    int selStart = richTextBox1.SelectionStart;
    int selLen = richTextBox1.SelectionLength;

    // 按位置拆分字符串后拼接标签
    string wrappedContent = $"<red>{fullText.Substring(selStart, selLen)}</red>";
    richTextBox1.Text = fullText.Substring(0, selStart) + wrappedContent + fullText.Substring(selStart + selLen);
    
    // 可选:选中刚添加标签后的内容,方便后续编辑
    richTextBox1.Select(selStart, wrappedContent.Length);
}

内容的提问来源于stack exchange,提问作者Nikola Marinov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 17:48:02