2013-03-01 54 views
2

我的程序有兩種關閉方式,一種是右上角的「X」,另一種是「退出」按鈕。現在,當滿足某個條件時按下其中任何一個,會彈出一條消息通知用戶他們還沒有保存。如果他們保存,消息將不會彈出,並且程序正常關閉。現在,當消息彈出時,用戶會收到帶有「是」和「否」按鈕的消息框。如果按下「是」,程序需要保存。如果按下「否」,則程序需要取消用戶按下「X」或「退出」按鈕時發起的關閉事件。取消關閉C#表格

這樣做的最好方法是什麼?

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

private void TryClose() 
{ 
    if (saved == false) 
    { 
     //You forgot to save 
     //Turn back to program and cancel closing event 
    } 
} 
+1

的WinForms? WPF?別的東西? – 2013-03-01 23:15:44

+0

我的不好,我改變了OP。 – 2013-03-01 23:16:51

+0

假設它是WinForms,請參閱此問題:http://stackoverflow.com/questions/4851156/window-close-events-in-a-winforms-application – 2013-03-01 23:18:17

回答

4

FormClosingEventArgs包括一個Cancel屬性。只需設置e.Cancel = true;以防止表單關閉。

private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
{ 
    if (!saved) 
     e.Cancel = true; 
} 

編輯迴應評論:

因爲你的目標是讓相同的「保存方法」中使用,我會改變它的成功返回bool

private bool SaveData() 
{ 
    // return true if data is saved... 
} 

然後,你可以寫:

private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
{ 
    // Cancel if we can't save 
    e.Cancel = !this.SaveData(); 
} 

如果需要,您的按鈕處理程序等都可以調用SaveData()

+0

問題是保存功能是從方法嵌入的,並且該方法沒有'FormClosingEventArgs e'屬性。更多按鈕或事件使用保存功能。 – 2013-03-01 23:19:48

0

要取消closing事件剛剛成立的Cancel屬性trueFormClosingEventArgs實例

if (!saved) { 
    // Message box 
    e.Cancel = true; 
} 
1

這將你需要的東西:

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

private bool TryClose() 
{ 
    return DialogResult.Yes == MessageBox.Show("Are you sure?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); 
} 
+0

覆蓋可能時,您不應使用事件。 – BlueMonkMN 2013-03-01 23:21:01

0

您可以關閉從退出按鈕調用。然後像其他人所說的那樣在Forms.FormClosing事件中處理關閉。這將同時處理退出按鈕單擊並形成從 「X」

0

覆蓋OnFormClosing閉幕:

protected override void OnFormClosing(FormClosingEventArgs e) 
{ 
    if (saved == true) 
    { 
     Environment.Exit(0); 
    } 
    else /* consider checking CloseReason: if (e.CloseReason != CloseReason.ApplicationExitCall) */ 
    { 
     //You forgot to save 
     e.Cancel = true; 
    } 
    base.OnFormClosing(e); 
} 
0
private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
    { 
     e.Cancel = !TryClose(); 
    } 

    private bool TryClose() 
    { 
     if (!saved) 
     { 
      if (usersaidyes) 
      { 
       // save stuff 
       return true; 
      } 
      else if (usersaidno) 
      { 
       // exit without saving 
       return false; 
      } 
      else 
      { 
       // user cancelled closing 
       return true; 
      } 
     } 
     return true; 
    } 
+0

覆蓋可能時,您不應使用事件。 – BlueMonkMN 2013-03-01 23:21:34