FormClosing not called when clicking Big Red X in the corner
Asked Answered
D

2

5

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.

Drape answered 16/8, 2011 at 17:17 Comment(1)
Has the event been delegated to the handler?Amadavat
S
9

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();
}
Squeeze answered 16/8, 2011 at 17:32 Comment(1)
Awesome, that did it. I assumed a Form would already be subscribed to this event when it was created.Drape
B
1

Make sure that you're correctly subscribing to the FormClosing event.

You must have on your MainWin dialog (tipically in the constructor), something like this:

this.FormClosing += new FormClosingEventHandler(MainWin_FormClosing);

Hope it helps.

Beatify answered 16/8, 2011 at 17:33 Comment(1)
Or the shorter version this.FormClosing += MainWin_FormClosing; :)Noontime

© 2022 - 2024 — McMap. All rights reserved.