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

如何用C#实现逗号触发的关键词框?RichTextBox能否实现该功能?

使用RichTextBox实现关键词自动转标签框功能

完全可以用RichTextBox实现你要的需求,核心思路是监听输入事件、检测逗号触发、提取关键词并应用样式替换文本,下面是具体实现方案:

实现步骤

  • 监听RichTextBox的KeyPress事件,捕捉逗号输入动作
  • 提取光标前的有效关键词(过滤多余空格)
  • 删除原关键词文本,替换为带样式的标签格式
  • 恢复默认输入样式,定位光标到标签后继续输入

代码示例(WinForms)

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
        // 绑定按键事件
        richTextBox1.KeyPress += RichTextBox1_KeyPress;
    }

    private void RichTextBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        // 仅响应逗号输入
        if (e.KeyChar != ',') return;

        // 阻止默认逗号输入,我们要替换为标签
        e.Handled = true;

        int cursorPos = richTextBox1.SelectionStart;
        string textBeforeCursor = richTextBox1.Text.Substring(0, cursorPos);

        // 提取最后一个空格后的内容作为关键词,处理连续空格情况
        int lastSpaceIdx = textBeforeCursor.LastIndexOf(' ');
        string keyword = textBeforeCursor.Substring(lastSpaceIdx + 1).Trim();

        // 空关键词直接跳过
        if (string.IsNullOrWhiteSpace(keyword)) return;

        // 删除原关键词文本
        richTextBox1.Select(lastSpaceIdx + 1, cursorPos - (lastSpaceIdx + 1));
        richTextBox1.SelectedText = string.Empty;

        // 插入带样式的标签
        richTextBox1.SelectionStart = lastSpaceIdx + 1;
        // 设置标签样式:浅蓝背景、深灰文字、加粗
        richTextBox1.SelectionBackColor = Color.LightBlue;
        richTextBox1.SelectionColor = Color.DarkSlateGray;
        richTextBox1.SelectionFont = new Font(richTextBox1.Font, FontStyle.Bold);
        // 用空格分隔标签,保持视觉区分
        richTextBox1.SelectedText = $" {keyword} ";

        // 恢复默认输入样式
        richTextBox1.SelectionBackColor = richTextBox1.BackColor;
        richTextBox1.SelectionColor = richTextBox1.ForeColor;
        richTextBox1.SelectionFont = richTextBox1.Font;

        // 定位光标到标签末尾,继续输入
        richTextBox1.SelectionStart = richTextBox1.Text.Length;
    }
}

额外说明

  • 如果需要圆角标签:RichTextBox原生不支持圆角绘制,若要实现更美观的圆角效果,可通过两种方式补充:
    1. 使用Unicode圆角框字符包裹关键词(如「关键词」),但样式局限性较大
    2. 重写RichTextBox的Paint事件,自定义绘制标签背景,这种方式需要跟踪每个标签的位置和范围,实现复杂度较高
  • 可扩展优化:添加标签删除逻辑(如选中标签后按退格键直接删除整个标签)、限制关键词长度、支持回车触发标签转换等

内容的提问来源于stack exchange,提问作者Lotus Rex

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 05:05:19