C# wpf 点关闭的时候弹出对话框 点确定才关闭窗口

重写OnClosing事件

namespace WpfApp3
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("你确定要关闭这个窗口吗?", "关闭窗口", MessageBoxButton.OKCancel, MessageBoxImage.Question);

            // 如果用户点击了“取消”,则阻止窗口关闭
            if (result == MessageBoxResult.Cancel)
            {
                e.Cancel = true; // 阻止窗口关闭
            }
            else
            {
                // 如果用户点击了“确定”,则继续关闭窗口
                base.OnClosing(e); // 调用基类的OnClosing以确保正常处理(如果有的话)
            }
        }
    }
}

 

posted @ 2025-03-09 15:23  竹楼风雨声  阅读(68)  评论(0)    收藏  举报