C#表单不会在FormClosing事件上关闭

时间:2010-10-04 02:09:25

标签: c# .net winforms formclosing

将以下代码添加到我的代码隐藏后,我的表单不会被关闭。

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

2 个答案:

答案 0 :(得分:3)

听起来好像添加上面的代码就会阻止Form关闭。如果是这样,那么最可能的原因是MyTHreadingObj.Dispose()语句抛出异常。尝试在try / catch中包装语句,看看是否是这种情况

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

答案 1 :(得分:0)

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