简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM