FormClosing not called when clicking Big Red X in the corner

Almo picture Almo · Aug 16, 2011 · Viewed 7.7k times · Source

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.

Answer

Vladimir picture Vladimir · Aug 16, 2011

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