Search code examples
c#winformsformclosing

FormClosing not called when clicking Big Red X in the corner


I found this:

Button with an X at the upper-right corner of the form, how to catch this event @ C#

Which says I should use the FormClosing event to find out when the window is closing because of a click on the X.

But my event code never gets called:

private void MainWin_FormClosing(Object sender, FormClosingEventArgs e)
{
    m_closeThread = true;
    Application.Exit();
}

I must be missing something basic, but I don't know what.


Solution

  • You must either subscribe to the event like:

    this.FormClosing += this.MainWin_FormClosing;
    

    in the form's constructor (or somewhere), or use:

    override void OnFormClosing(FormClosingEventArgs e)
    {
        m_closeThread = true;
        Application.Exit();
    }