C# 中的訊息框

Muhammad Maisam Abbas 2023年10月12日
C# 中的訊息框

本教程將討論如何在 C# 中建立帶有選項的訊息框。

在 C# 中使用 MessageBox 類建立一個訊息框

MessageBox在 C# 中顯示一個訊息視窗。如果要建立帶有選項的訊息框,則可以在 MessageBox 類建構函式的引數中傳遞 MessageBoxButton.YesNo 列舉。下面的程式碼示例向我們展示瞭如何使用 C# 中的 MessageBox 類建立帶有選項的訊息框。

using System.Windows.Forms;

namespace messagbox {
  static class Program {
    static void Main() {
      Application.EnableVisualStyles();
      DialogResult dr = MessageBox.Show("Are you happy now?", "Mood Test", MessageBoxButtons.YesNo);
      switch (dr) {
        case DialogResult.Yes:
          MessageBox.Show("That is Fantastic");
          break;
        case DialogResult.No:
          MessageBox.Show("Why Not?");
          break;
      }
    }
  }
}

輸出:

C# 訊息框 1

C# 訊息框 2

在上面的程式碼中,我們將 MessageBox.Show() 函式的結果儲存在 DialogResult 列舉的 dr 例項中。DialogResult 列舉包含代表對話方塊返回值的識別符號。我們使用 switch 語句檢查 MessageBox.Show() 函式返回的值,併為每個所選選項顯示另一個訊息框。

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

相關文章 - Csharp GUI