工具欄加粗按鈕按下凹陷(狀態激活),輸入文字自動加粗;光標移動到非加粗文本按鈕彈起,點擊按鈕切換當前選區/輸入位置加粗狀態。
private void btnBold_Click(object sender, EventArgs e) {
Font currentFont = richTextBox.SelectionFont;
FontStyle newStyle = FontStyle.Regular;
if (currentFont != null) {
newStyle = currentFont.Style ^ FontStyle.Bold; // 異或切換
}
richTextBox.SelectionFont = new Font(currentFont ?? richTextBox.Font, newStyle);
btnBold.Checked = (newStyle & FontStyle.Bold) != 0; // 同步按鈕狀態
}
private void richTextBox_SelectionChanged(object sender, EventArgs e) {
Font font = richTextBox.SelectionFont;
btnBold.Checked = (font != null && (font.Style & FontStyle.Bold) != 0);
// 同理處理斜體、下劃線等按鈕
}
CheckOnClick = true、FlatStyle = FlatStyle.Standard,點擊自動呈現按下/彈起視覺效果。SelectionFont 為 null 表示選區混合格式,按鈕顯示為未選中(或半選中狀態需自繪)。FontStyle 位運算:^ 切換,& 判斷,| 添加。richTextBox.Rtf 屬性。此模式可擴展至字體、字號、顏色等所有富文本格式控件。