向Windows.Forms退出按钮添加功能?

Ben*_*erg 3 c# button exit winforms

在C#.NET 4.0中编程是我最近的热情,我想知道如何在标准的Windows.Forms Exit按钮(表单右上角的红色X)中添加功能.

我找到了一种禁用按钮的方法,但由于我认为它会影响用户体验,我想将一些功能联系起来.

如何禁用退出按钮:

    #region items to disable quit-button
    const int MF_BYPOSITION = 0x400;
    [DllImport("User32")]
    private static extern int RemoveMenu(IntPtr hMenu, int nPosition, int wFlags);
    [DllImport("User32")]
    private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
    [DllImport("User32")]
    private static extern int GetMenuItemCount(IntPtr hWnd);
    #endregion 
Run Code Online (Sandbox Code Playgroud)

...

    private void DatabaseEditor_Load(object sender, EventArgs e)
    {
        this.graphTableAdapter.Fill(this.diagramDBDataSet.Graph);
        this.intervalTableAdapter.Fill(this.diagramDBDataSet.Interval);

        // Disable quit-button on load
        IntPtr hMenu = GetSystemMenu(this.Handle, false);
        int menuItemCount = GetMenuItemCount(hMenu);
        RemoveMenu(hMenu, menuItemCount - 1, MF_BYPOSITION);
    }
Run Code Online (Sandbox Code Playgroud)

但是,在应用程序退出标准退出按钮之前,我如何附加方法.我想在退出Windows窗体之前XmlSerialize一个List.

Ser*_*glu 5

如果要在表单关闭之前编写代码,请使用FormClosing事件

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {

    }
Run Code Online (Sandbox Code Playgroud)


Pau*_*sey 5

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
   if(MessageBox.Show("Are you sure you want to exit?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
   {
       e.Cancel = true;
   }
}
Run Code Online (Sandbox Code Playgroud)