2013-03-01 66 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