2011-12-28 35 views
1

當窗口關閉時,我正在調用方法TryClose來顯示對話框。但是當我點擊Cancel該應用程序關閉。任何想法只是爲了「隱藏」對話框,不做別的事情?MessageBoxResult按鈕取消關閉應用程序

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; 
    } 
} 
+0

嘗試添加一個默認情況。 – 2011-12-28 18:22:32

回答

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(); 
} 
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; 
} 
+1

這裏沒有'e'。 – 2011-12-28 18:24:58

相關問題