我使用Microsoft Visual C#2008 Express的。

在我的主要形式,还有的是X按钮关闭窗体右上角。如何将代码添加到该按钮?在我的菜单,我有一个“退出”项目,它有一个清理和关闭数据库,我的代码。我怎么同一个代码,如果用户选择的是作为一种退出添加到这个按钮?

谢谢!

-Adeena

有帮助吗?

解决方案

使用的FormClosing事件应当捕捉闭合形式的任何方法。

其他提示

在您的表单设计视图,在属性窗口中,选择活动按钮,向下滚动到“FormClosed”和“的FormClosing”事件。

窗体关闭后FormClosed被调用。

闭合形式之前的FormClosing被调用,也允许您取消结束时,保持开放形式:

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

如果你要问用户“你确定要做到接近这种形式?”,然后使用FormClosing,在这里你可以设置Cancel = True和形式将照常开放。

如果你想关闭一些资源,只有当形式肯定是关闭的,那么你用FormClosed事件。

如果你在整个代码的控制,那么它那种无所谓。但你不希望发生的是使用FormClosing当事件的其他处理器将保持开放的形式来清理资源。

的FormClosing / FormClosed让你看为形式,其可以与应用退出重合事件。然而,还有另外一个事件时,可以线了称为Application.ApplicationExit。

在你的主要方法:

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

}

使用您的WinForm的闭事件。

此代码将捕获的“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);
}

双击退出按钮在form'design然后 简单地调用Dispose()方法

表单动作方法 //

 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;
                     }
         }
 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();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top