如何在C#窗体中的退出按钮上添加代码?

7

我正在使用Microsoft Visual C# 2008 Express。

在我的主窗体中,右上角有一个X按钮用于关闭窗体。如何向此按钮添加代码?在我的菜单中,有一个“退出”项目,其中包含清理并关闭数据库的代码。如果用户选择这种方式退出,如何将相同的代码添加到此按钮?

谢谢!

- Adeena

9个回答

12

使用FormClosing事件可以捕获任何关闭窗体的方式。


8
在您的表单的设计视图中,在属性窗口中选择事件按钮并向下滚动到“FormClosed”和“FormClosing”事件。
“FormClosed”在关闭表单后调用。
“FormClosing”在关闭表单之前调用,并允许您取消关闭,保持表单打开状态。
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = true;
}

1
如果你想要询问用户“您确定要关闭此表单吗?”,那么请使用FormClosing,在这里你可以设置Cancel = True,这样表单就会保持打开状态。
如果你只想在表单被彻底关闭时才关闭某些资源,那么你需要使用FormClosed事件。
如果你掌控整个代码,那么这有点无关紧要。但是你不希望在另一个事件处理程序将表单保持打开状态时使用FormClosing来清理资源。

0
 You can use form closing events choose or set closing event in  properties window      
 You can add dialog conditions based on what task you want to perform before closing form

private void Form1_FormClosing(object sender,FormClosingEventArgs e)
{
Application.Exit();
//you can also use Application.ExitThread();
}

0

FormClosing/FormClosed让您观察该窗体的事件,这可能与应用程序退出相重合。但是,还有另一个事件可以连接,称为Application.ApplicationExit。

在您的Main方法中:

Application.ApplicationExit += Application_ApplicationExit;

...

private static void Application_ApplicationExit(object sender, EventArgs e) {

  // do stuff when the application is truly exiting, regardless of the reason

}

0

这段代码将捕获用户在窗体上点击“X”或使用Alt-F4的操作,以便您可以执行某些操作。我不得不使用它,因为我需要调用我的关闭事件来执行某些操作,但是当使用FormClosing事件时,由于竞争事件,它不会调用它。

/// <summary>
/// This code captures the 'Alt-F4' and the click to the 'X' on the ControlBox
/// and forces it to call MyClose() instead of Application.Exit() as it would have.
/// This fixes issues where the threads will stay alive after the application exits.
/// </summary>
public const int SC_CLOSE = 0xF060;
public const int WM_SYSCOMMAND = 0x0112;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
    if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
        MyClose();

    base.WndProc(ref m);
}

0

在窗体设计中双击退出按钮,然后简单地调用Dispose()方法


0
使用您的Winform的Closed-Event。

是“FormClosed”还是“FormClosing”?如果我只是关闭数据库之类的事情,那么这是否重要呢? - adeena
抱歉,打错了,我是指Closed-Event。但我刚刚读到它被.NET 2.0及以上版本中的FormClosed-Event所取代。 - Stephan Keller

0

表单提交方式 //

 protected override void OnFormClosing(FormClosingEventArgs e)

          {
          base.OnFormClosing(e);

          if (e.CloseReason == CloseReason.WindowsShutDown) return;

               switch (MessageBox.Show(this, "Are you sure you want to exit?", "Exit", MessageBoxButtons.YesNo))
                     {
                       case DialogResult.No:
                           e.Cancel = true;
                           break;
                     default:
                          break;
                     }
         }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接