简体   繁体   English

C#表单在FormClosing事件上未关闭

[英]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. 听起来像添加上述代码会阻止您的Form关闭。 If so then the most likely cause is that the MyTHreadingObj.Dispose() statement is throwing an exception. 如果是这样,那么最可能的原因是MyTHreadingObj.Dispose()语句引发异常。 Try wrapping the statement in a try/catch and seeing if this is the case 尝试将语句包装在try / catch中,看看是否是这种情况

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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