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

C# WinForms 模式對話框完整解析(四)

     編輯:關於C語言

簡化版對話框實作

利用按鈕 DialogResult 屬性自動處理關閉邏輯,大幅減少代碼:


// 建構函式中設置
this.buttonOK.DialogResult = DialogResult.OK;
this.buttonCancel.DialogResult = DialogResult.Cancel;

// 僅需處理 OK 按鈕驗證邏輯
private void buttonOK_Click(object sender, EventArgs e)
{
    if (string.IsNullOrWhiteSpace(textBoxPath.Text))
    {
        MessageBox.Show("輸入的路徑資訊不正確!");
        textBoxPath.Focus();
        this.DialogResult = DialogResult.None; // 阻止關閉
    }
}
// Cancel 按鈕無需代碼,自動返回 DialogResult.Cancel

.NET Framework 內建常用對話框

類別功能繼承自模式顯示方法
MessageBox訊息方塊(文字、按鈕、圖示)-MessageBox.Show() 靜態方法
OpenFileDialog開啟檔案FileDialogShowDialog()
SaveFileDialog儲存檔案FileDialogShowDialog()
FolderBrowserDialog選擇資料夾CommonDialogShowDialog()
FontDialog字型選擇CommonDialogShowDialog()
ColorDialog顏色選擇CommonDialogShowDialog()
PageSetupDialog列印頁面設定CommonDialogShowDialog()
PrintDialog列印設定CommonDialogShowDialog()
PrintPreviewDialog列印預覽FormShowDialog() / Show()

MessageBox 進階用法


// 完整參數版本
DialogResult result = MessageBox.Show(
    owner: this,
    text: "確定要刪除嗎?",
    caption: "確認刪除",
    buttons: MessageBoxButtons.YesNoCancel,
    icon: MessageBoxIcon.Warning,
    defaultButton: MessageBoxDefaultButton.Button2,
    options: MessageBoxOptions.RightAlign,
    helpFilePath: "help.chm",
    navigator: HelpNavigator.Topic,
    param: "delete_topic"
);

PrintPreviewDialog 特殊性

繼承自 Form,除 ShowDialog() 外,亦可用 Show() 非模式顯示。

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