首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET RichTextBox 關鍵字高亮顯示實作教學

     編輯:ASP.NET 基礎

前言

Windows Forms 的 `RichTextBox` 控制項支援富文本顯示與編輯,常用於關鍵字搜尋高亮、日誌關鍵字標記、程式碼語法著色等場景。本文詳細說明使用 `Find`、`SelectionStart`、`SelectionLength`、`SelectionColor`、`SelectionFont` 實現關鍵字高亮的完整技巧。

一、核心 API 速查

屬性/方法說明
Find(string)尋找字串,回傳起始索引 (找不到回傳 -1)
Find(string, int, int, RichTextBoxFinds)進階尋找:指定搜尋範圍、大小寫、整字匹配等選項
SelectionStart取得/設定選取區塊起始位置
SelectionLength取得/設定選取區塊長度
SelectionColor取得/設定選取文字前景色
SelectionBackColor取得/設定選取文字背景色
SelectionFont取得/設定選取文字字型
SelectAll()全選內容
DeselectAll()取消選取

二、基本高亮實作:單一關鍵字

/// 
/// 高亮顯示指定關鍵字 (單次搜尋)
/// 
private void HighlightKeyword(string keyword)
{
    if (string.IsNullOrEmpty(keyword)) return;
    
    // 1. 尋找關鍵字位置
    int startIndex = richTextBox1.Find(keyword);
    
    // 2. 找到才處理
    if (startIndex >= 0)
    {
        // 3. 設定選取範圍
        richTextBox1.SelectionStart = startIndex;
        richTextBox1.SelectionLength = keyword.Length;
        
        // 4. 套用樣式
        richTextBox1.SelectionColor = Color.Red;
        richTextBox1.SelectionBackColor = Color.Yellow;
        // richTextBox1.SelectionFont = new Font("Consolas", 10, FontStyle.Bold);
    }
}

三、進階高亮:所有出現位置 (不區分大小寫)

/// 
/// 高亮所有匹配的關鍵字
/// 
private void HighlightAllKeywords(string keyword, Color? foreColor = null, Color? backColor = null, Font font = null)
{
    if (string.IsNullOrEmpty(keyword)) return;
    
    Color fColor = foreColor ?? Color.Red;
    Color bColor = backColor ?? Color.Yellow;
    Font fFont = font ?? new Font(richTextBox1.Font, FontStyle.Bold);
    
    int startIndex = 0;
    while (true)
    {
        // 從上次位置之後繼續搜尋,不區分大小寫
        int foundIndex = richTextBox1.Find(keyword, startIndex, RichTextBoxFinds.None);
        
        if (foundIndex < 0) break; // 找不到結束
        
        // 設定選取範圍
        richTextBox1.SelectionStart = foundIndex;
        richTextBox1.SelectionLength = keyword.Length;
        
        // 套用樣式
        richTextBox1.SelectionColor = fColor;
        richTextBox1.SelectionBackColor = bColor;
        richTextBox1.SelectionFont = fFont;
        
        // 下一次從當前匹配結束位置開始
        startIndex = foundIndex + keyword.Length;
    }
    
    // 還原游標位置
    richTextBox1.SelectionStart = richTextBox1.TextLength;
    richTextBox1.SelectionLength = 0;
    richTextBox1.ScrollToCaret();
}

四、RichTextBoxFinds 選項詳細

組合使用:RichTextBoxFinds.MatchCase | RichTextBoxFinds.WholeWord

五、完整範例:搜尋框即時高亮

public partial class Form1 : Form
{
    private string _lastKeyword = "";
    
    public Form1()
    {
        InitializeComponent();
        
        // 載入範例文字
        richTextBox1.Text = @"ASP.NET 是微軟開發的 Web 應用程式框架。
RichTextBox 可以顯示富文本內容。
使用 Find 方法可以搜尋關鍵字。
SelectionColor 可以改變文字顏色。";
    }
    
    private void txtSearch_TextChanged(object sender, EventArgs e)
    {
        string keyword = txtSearch.Text.Trim();
        
        // 關鍵字未改變則跳過
        if (keyword == _lastKeyword) return;
        _lastKeyword = keyword;
        
        // 1. 先移除所有現有高亮 (還原預設樣式)
        RemoveAllHighlights();
        
        // 2. 應用新高亮
        if (!string.IsNullOrEmpty(keyword))
        {
            HighlightAllKeywords(keyword, Color.White, Color.DodgerBlue);
        }
    }
    
    /// 
    /// 移除所有高亮,還原預設樣式
    /// 
    private void RemoveAllHighlights()
    {
        richTextBox1.SelectAll();
        richTextBox1.SelectionColor = richTextBox1.ForeColor;
        richTextBox1.SelectionBackColor = richTextBox1.BackColor;
        richTextBox1.SelectionFont = richTextBox1.Font;
        richTextBox1.DeselectAll();
    }
}

六、效能優化:大文本處理

  • 暫停重繪:大量高亮操作前呼叫 `richTextBox1.SuspendLayout()`,結束後 `ResumeLayout()`。
  • 批次處理:收集所有匹配位置陣列,單次迴圈套用樣式,避免重複 `Find` 呼叫。
  • 虛擬化:超大文本 (1MB+) 建議使用第三方元件 (ScintillaNET, FastColoredTextBox) 支援虛擬化渲染。

七、常見問題

旗標說明
None預設:區分大小寫、部分匹配
MatchCase區分大小寫
WholeWord整字匹配 (邊界為非單字字元)
Reverse反向搜尋 (從尾部向前)
NoHighlight不自動反白選取區塊 (僅回傳索引)
問題原因解決
高亮不生效RichTextBox 未獲焦點 / HideSelection=true設定 `HideSelection = false` 或先 `Focus()`
多次高亮顏色疊加錯誤未清除舊高亮每次搜尋前呼叫 `RemoveAllHighlights()`
中文關鍵字找不到編碼不匹配 / 全形半形差異確保字串編碼一致,或使用 `WholeWord` 選項
SelectionFont 設定後整行變粗RichTextBox 行內字型混用限制僅支援選取區塊統一字型,無法單一字元不同字型

八、WPF / ASP.NET 替代方案

平台控制項/方案關鍵 API
WPFRichTextBox + TextRange`TextRange.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red)`
ASP.NET WebFormsTextBox (無高亮) / 第三方編輯器CKEditor, TinyMCE, RadEditor 內建搜尋高亮
ASP.NET Core前端元件Vue/React + highlight.js / mark.js
BlazorMarkdown 編輯器 / QuillQuill 格式化 API

總結

WinForms `RichTextBox` 高亮核心公式:Find 定位 → SelectionStart/Length 選取 → SelectionColor/BackColor/Font 樣式化。關鍵細節:`RichTextBoxFinds` 選項控制匹配行為、搜尋前清除舊高亮、大文本效能優化。對於現代 Web 應用,建議將高亮邏輯前移至前端 (mark.js, highlight.js),後端僅提供純文本資料。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved