views:

58

answers:

2

Programming in C#.NET 4.0 is my latest passion, and I would like to know how to add functionality to the standard Windows.Forms Exit button (the red X in the upper right corner of the form).

I have found a way to disable the button, but since I think it compromises the user experiance, I would like to hook up some functionalities instead.

How to disable exit button:

    #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 

...

    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);
    }

But how on earth do I attach a method, before the application exits with the standard exit-button. I would like to XMLserailize a List before exiting the windows form.

+2  A: 

If you want to write codes before form closed, use FormClosing event

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {

    }
Serkan Hekimoglu
Thanx Serkan!That did the trick :)BR
BennySkogberg
Your welcome...
Serkan Hekimoglu
+3  A: 
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;
   }
}
Paul Creasey
Thanx Paul!That did the trick :)BR
BennySkogberg