Moon
Moon

Reputation: 35265

C# form doesn't close on FormClosing event

After I added the following code to my code-behind, my form doesn't get closed.

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
    MyThreadingObj.Dispose();
}

Upvotes: 1

Views: 1078

Answers (2)

IMMORTAL
IMMORTAL

Reputation: 2857

protected override void OnFormClosing(FormClosingEventArgs e)
        {            
            base.OnFormClosing(e);
            if (PreClosingConfirmation() == System.Windows.Forms.DialogResult.Yes)
            {
                Dispose(true);
                Application.Exit();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private DialogResult PreClosingConfirmation()
        {
            DialogResult res = System.Windows.Forms.MessageBox.Show(" Do you want to quit?          ", "Quit...", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            return res;
        }

Upvotes: 0

JaredPar
JaredPar

Reputation: 754505

It sounds like adding the above code prevents your Form from closing. If so then the most likely cause is that the MyTHreadingObj.Dispose() statement is throwing an exception. Try wrapping the statement in a try/catch and seeing if this is the case

try {
  MyThreadingObj.Dispose();
} catch ( Exception e ) { 
  Console.WriteLine(e);
}

Upvotes: 2

Related Questions