萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 自訂訊息框美化:取代內建 MessageBox 的完整實作

動機

Windows 內建 MessageBox.Show 外觀固定、無法客製化圖示、按鈕文字、字型、配色,且在高 DPI 下模糊。本文實作一個 完全可客製化的 CustomMessageBox,支援:

  • 三種預設風格:資訊 (Info)、詢問 (Question)、錯誤 (Error)
  • 自動依訊息長度調整寬度、按鈕自適應
  • 圖示來源:專案資源檔 (.resx)
  • 回傳 DialogResult 相容既有邏輯

表單設計 (frmMessageBox)

控制項名稱關鍵屬性
PictureBoxpicIconSizeMode=CenterImage, Dock=None
LabellblMessageAutoSize=False, Dock=Fill, TextAlign=MiddleLeft, Font=微軟正黑體 12pt
PanelpnlSingleBtnDock=Bottom, Height=50, Visible=False
Button (在 pnlSingleBtn)btnOKText=確定(&O), DialogResult=OK, Anchor=Bottom,Right
PanelpnlDoubleBtnDock=Bottom, Height=50, Visible=False
Button (在 pnlDoubleBtn)btnYesText=是(&Y), DialogResult=Yes
Button (在 pnlDoubleBtn)btnNoText=否(&N), DialogResult=No

列舉與建構函式

public enum MsgBoxStyle { Info, Question, Error }

public partial class CustomMessageBox : Form
{
    public CustomMessageBox(MsgBoxStyle style, string message)
    {
        InitializeComponent();

        switch (style)
        {
            case MsgBoxStyle.Info:
                picIcon.Image = Properties.Resources.info_32;
                Text = "提示";
                pnlSingleBtn.Visible = true;
                break;
            case MsgBoxStyle.Question:
                picIcon.Image = Properties.Resources.question_32;
                Text = "詢問";
                pnlDoubleBtn.Visible = true;
                break;
            case MsgBoxStyle.Error:
                picIcon.Image = Properties.Resources.error_32;
                Text = "錯誤";
                pnlSingleBtn.Visible = true;
                break;
        }

        lblMessage.Text = message;
        AdjustSize();
    }

    private void AdjustSize()
    {
        // 量測文字所需寬度
        using (Graphics g = CreateGraphics())
        {
            SizeF sz = g.MeasureString(lblMessage.Text, lblMessage.Font, 400);
            int reqWidth = (int)Math.Ceiling(sz.Width) + 80; // 圖示 + 邊距
            int minWidth = 300;
            this.Width = Math.Max(reqWidth, minWidth);

            // 置中按鈕面板
            int panelW = Math.Max(reqWidth - 40, 120);
            pnlSingleBtn.Width = panelW;
            pnlDoubleBtn.Width = panelW;

            // 雙按鈕平分寬度
            btnYes.Width = btnNo.Width = panelW / 2 - 10;
        }
    }

    // 靜態工廠方法,模仿 MessageBox.Show
    public static DialogResult Show(MsgBoxStyle style, string text, string caption = "")
    {
        using (var box = new CustomMessageBox(style, text))
        {
            if (!string.IsNullOrEmpty(caption)) box.Text = caption;
            return box.ShowDialog();
        }
    }

    public static DialogResult ShowInfo(string text) => Show(MsgBoxStyle.Info, text);
    public static DialogResult ShowQuestion(string text) => Show(MsgBoxStyle.Question, text);
    public static DialogResult ShowError(string text) => Show(MsgBoxStyle.Error, text);
}

使用範例

進階擴充:支援自訂按鈕文字、圖示、預設焦點

public class CustomMessageBoxOptions
{
    public MsgBoxStyle Style { get; set; } = MsgBoxStyle.Info;
    public string Message { get; set; }
    public string Title { get; set; }
    public string[] ButtonTexts { get; set; } = new[] { "確定" };
    public DialogResult[] ButtonResults { get; set; } = new[] { DialogResult.OK };
    public int DefaultButtonIndex { get; set; } = 0;
    public Image CustomIcon { get; set; }
    public Font MessageFont { get; set; }
    public Color BackColor { get; set; } = SystemColors.Window;
}

public static DialogResult ShowEx(CustomMessageBoxOptions opts)
{
    using (var box = new CustomMessageBoxEx(opts))
        return box.ShowDialog();
}

// 內部動態建立按鈕...
// 範例呼叫:
var result = CustomMessageBox.ShowEx(new CustomMessageBoxOptions
{
    Style = MsgBoxStyle.Question,
    Message = "儲存變更?",
    ButtonTexts = new[] { "儲存", "不儲存", "取消" },
    ButtonResults = new[] { DialogResult.Yes, DialogResult.No, DialogResult.Cancel },
    DefaultButtonIndex = 2
});

高 DPI 相容性

表單設計時啟用 AutoScaleMode = Font (預設),並在專案屬性 → Application → Manifest 勾選 DPI Awareness: Per Monitor V2。

對比總結

特性MessageBox.ShowCustomMessageBox
外觀客製化無完整支援
按鈕文字/數量固定組合任意
圖示來源系統預設資源檔/自訂 Image
字型/顏色系統預設可設定
高 DPI系統處理 (有時模糊)需自行處理縮放
非同步/非模態不支援可改為 Show() + 事件
copyright © 萬盛學電腦網 all rights reserved