`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); // 恢復選區
}
**WinForms 富文本樣式操作本質:位運算 + 重建 Font 對象 + 重新賦值。**