Add functionality to the Windows.Forms exit button?

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

I found a way to disable the button, but since I think this compromises the user experiment, I would like to enable some features.

How to disable the 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 can I attach a method before the application exits with a standard exit button. I would like to have an XmlSerialize List before exiting a Windows form.

+3
source share
3 answers
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;
   }
}
+4
source

, FormClosing

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {

    }
+5

The best way I've found is to create an EventHandler that will call the method you want to call.

In the constructor:

this.Closed += new EventHandler(theWindow_Closed);

Then you create a method:

private void theWindow_Closed(object sender, System.EventArgs e)
{
    //do the closing stuff
}
+1
source

Source: https://habr.com/ru/post/1752775/


All Articles