首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

WinForms RichTextBox:移除特定字體樣式(如 Bold)保留其它樣式

     編輯:程式設計疑難解答

需求

`RichTextBox` 選區字體為 `Bold | Underline`,需**取消 Bold 保留 Underline**,類似 Word 中點擊 B 鈕切換。

核心代碼

// 獲取當前選區字體
Font currentFont = richTextBox.SelectionFont;
if (currentFont != null) {
    // 位運算移除 Bold 標誌
    FontStyle newStyle = currentFont.Style & ~FontStyle.Bold;
    // 構建新字體(保留字體族、大小)
    richTextBox.SelectionFont = new Font(currentFont.FontFamily, currentFont.Size, newStyle);
}

封裝為通用切換方法

void ToggleFontStyle(FontStyle style) {
    Font font = richTextBox.SelectionFont;
    if (font == null) return; // 選區混合字體時為 null,需逐字符處理
    
    FontStyle newStyle = font.Style ^ style; // XOR 切換:有則除,無則加
    richTextBox.SelectionFont = new Font(font.FontFamily, font.Size, newStyle);
}

// 使用:點擊「加粗」按鈕
btnBold.Click += (s, e) => ToggleFontStyle(FontStyle.Bold);

進階:混合字體選區處理

當選區包含多種字體時 `SelectionFont` 返回 `null`,需遍歷字符:

void ToggleFontStyleMixed(FontStyle style) {
    int start = richTextBox.SelectionStart;
    int len = richTextBox.SelectionLength;
    for (int i = start; i < start + len; i++) {
        richTextBox.Select(i, 1);
        Font font = richTextBox.SelectionFont;
        if (font != null) {
            FontStyle newStyle = font.Style ^ style;
            richTextBox.SelectionFont = new Font(font.FontFamily, font.Size, newStyle);
        }
    }
    richTextBox.Select(start, len); // 恢復選區
}

關鍵點

  • `FontStyle` 是 `[Flags]` 枚舉,支援位運算:`|` (加)、`& ~` (除)、`^` (切換)。
  • `SelectionFont` / `SelectionColor` 僅在選區**純淨**時返回值,混合時為 `null`。
  • 構建新 `Font` 時必須保留 `FontFamily` 和 `Size`,否則字體會重置為默認。

**WinForms 富文本樣式操作本質:位運算 + 重建 Font 對象 + 重新賦值。**

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