MessageBoxResult按钮取消关闭应用程序

时间:2011-12-28 18:15:36

标签: c# wpf messagebox

当窗口关闭时,我正在调用方法TryClose来显示对话框。但是当我点击Cancel应用程序关闭时。任何想法只是为了“隐藏”对话而不做其他事情?

public void TryClose()
{
    MessageBoxResult result = MessageBox.Show("Do you want to save changes?", appName, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);

    switch (result)
    {
        case MessageBoxResult.Yes:
            SaveAs();
            break;
        case MessageBoxResult.No:
            this.Close();
            break;
    }
}

2 个答案:

答案 0 :(得分:1)

将您的代码更改为:

public bool TryClose()
{
    MessageBoxResult result = MessageBox.Show("Do you want to save changes?", appName, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);

   switch (result)
   {
       case MessageBoxResult.Yes:
           SaveAs();
           return false;
       case MessageBoxResult.No:
           this.Close();
           return false;
   }

   return true;
}

在结束事件处理程序中,输入:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = TryClose();
}

答案 1 :(得分:0)

private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
   TryClose(e);
}

然后:

switch (result)
{
    case MessageBoxResult.Yes:
        SaveAs();
        break;
    case MessageBoxResult.No:
        this.Close();
        break;
    default:
        e.Cancel=true;
        break;
}