利用按鈕 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
| 類別 | 功能 | 繼承自 | 模式顯示方法 |
|---|---|---|---|
| MessageBox | 訊息方塊(文字、按鈕、圖示) | - | MessageBox.Show() 靜態方法 |
| OpenFileDialog | 開啟檔案 | FileDialog | ShowDialog() |
| SaveFileDialog | 儲存檔案 | FileDialog | ShowDialog() |
| FolderBrowserDialog | 選擇資料夾 | CommonDialog | ShowDialog() |
| FontDialog | 字型選擇 | CommonDialog | ShowDialog() |
| ColorDialog | 顏色選擇 | CommonDialog | ShowDialog() |
| PageSetupDialog | 列印頁面設定 | CommonDialog | ShowDialog() |
| PrintDialog | 列印設定 | CommonDialog | ShowDialog() |
| PrintPreviewDialog | 列印預覽 | Form | ShowDialog() / Show() |
// 完整參數版本
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"
);
繼承自 Form,除 ShowDialog() 外,亦可用 Show() 非模式顯示。