温馨提示×

如何在C#中优雅地处理确认对话框

c#
小樊
83
2024-09-04 13:53:31
栏目: 编程语言

在C#中,可以使用Windows Forms或WPF来创建一个确认对话框

  1. 使用Windows Forms的MessageBox类:
using System;
using System.Windows.Forms;

namespace ConfirmDialogExample
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            DialogResult result = MessageBox.Show("你确定要继续吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                Console.WriteLine("用户点击了'是'按钮");
            }
            else if (result == DialogResult.No)
            {
                Console.WriteLine("用户点击了'否'按钮");
            }
        }
    }
}
  1. 使用WPF的MessageBox类(需要引用System.Windows.Forms.dll):
using System;
using System.Windows;
using System.Windows.Forms;

namespace ConfirmDialogExample
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            MessageBoxResult result = MessageBox.Show("你确定要继续吗?", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                Console.WriteLine("用户点击了'是'按钮");
            }
            else if (result == MessageBoxResult.No)
            {
                Console.WriteLine("用户点击了'否'按钮");
            }
        }
    }
}

这两种方法都会显示一个包含“是”和“否”按钮的对话框。根据用户的选择,程序将执行相应的操作。请注意,为了使用这些功能,您需要添加对System.Windows.FormsSystem.Windows的引用。

0