我正在使用Microsoft Visual C# 2008 Express。
在我的主窗体中,右上角有一个X按钮用于关闭窗体。如何向此按钮添加代码?在我的菜单中,有一个“退出”项目,其中包含清理并关闭数据库的代码。如果用户选择这种方式退出,如何将相同的代码添加到此按钮?
谢谢!
- Adeena
使用FormClosing事件可以捕获任何关闭窗体的方式。
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
}
FormClosing
,在这里你可以设置Cancel = True
,这样表单就会保持打开状态。FormClosed
事件。FormClosing
来清理资源。 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();
}
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
}
这段代码将捕获用户在窗体上点击“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);
}
在窗体设计中双击退出按钮,然后简单地调用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;
}
}