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

C# FontDialog 字型對話框完整應用:屬性、事件與 RichTextBox 字體套用實戰

     編輯:關於C#

常用屬性速查表

屬性功能建議值
ShowColor顯示顏色下拉選單true
AllowScriptChange允許切換字元集(中文/日文等)true
Font預設/回傳選取字型綁定 RichTextBox.SelectionFont
Color預設/回傳選取顏色綁定 RichTextBox.SelectionColor
MinSize/MaxSize限制字號範圍8 / 72
ShowEffects顯示底線/刪除線/顏色true
ShowApply顯示「套用」按鈕(需處理 Apply 事件)視需求
ShowHelp顯示「說明」按鈕true

事件

  • Apply:使用者按「套用」時觸發,即時預覽。
  • HelpRequest:按「說明」觸發,可開啟線上文件或自訂說明視窗。

最小可用範例:套用至 RichTextBox 選取文字


private void btnFont_Click(object sender, EventArgs e)
{
    using (var dlg = new FontDialog())
    {
        dlg.Font = richTextBox.SelectionFont ?? richTextBox.Font;
        dlg.Color = richTextBox.SelectionColor;
        dlg.ShowColor = true;
        dlg.AllowScriptChange = true;
        dlg.ShowEffects = true;
        dlg.MinSize = 8;
        dlg.MaxSize = 72;

        if (dlg.ShowDialog() == DialogResult.OK)
        {
            richTextBox.SelectionFont = dlg.Font;
            richTextBox.SelectionColor = dlg.Color;
        }
    }
}

進階:即時預覽(Apply 事件)


private FontDialog fontDlg;

private void btnFont_Click(object sender, EventArgs e)
{
    if (fontDlg == null)
    {
        fontDlg = new FontDialog { ShowApply = true, ShowColor = true };
        fontDlg.Apply += FontDlg_Apply;
    }
    fontDlg.Font = richTextBox.SelectionFont ?? richTextBox.Font;
    fontDlg.Color = richTextBox.SelectionColor;
    fontDlg.ShowDialog(this);
}

private void FontDlg_Apply(object sender, EventArgs e)
{
    richTextBox.SelectionFont = fontDlg.Font;
    richTextBox.SelectionColor = fontDlg.Color;
}

protected override void Dispose(bool disposing)
{
    if (disposing) fontDlg?.Dispose();
    base.Dispose(disposing);
}

常見問題

  • SelectionFont 為 null:選取區塊包含多種字型 → 回傳 null。建議用 richTextBox.Font 作為預設值。
  • FontDialog 為 Modal 對話方塊,ShowDialog 會阻塞;若需非模態請改用自訂表單或 WPF FontDialog(需引用 System.Windows.Forms)。
  • 中文字型名稱顯示為英文(如 "Microsoft JhengHei" 顯示 "Microsoft JhengHei UI")屬正常行為,實際套用無誤。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved