WinForms app not closing completely
这是我的程序类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | static class Program { private class MyAppContext : ApplicationContext { public MyAppContext() { //Exit delegate Application.ApplicationExit += new EventHandler(this.OnApplicationExit); //Show the main form MainForm main = new MainForm(); main.Show(); } private void OnApplicationExit(object sender, EventArgs e) { //Cleanup code... } } [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MyAppContext()); } } |
当我在调试模式下运行应用程序并关闭它时,主窗体会关闭,但应用程序仍在运行,我必须单击
在主窗体中,我所做的只是:
1 2 3 4 5 | protected override void OnFormClosed(FormClosedEventArgs e) { base.OnFormClosed(e); Application.Exit(); } |
我做错了什么?
问题在于继承 AppContext,不知道为什么需要它。建议您在没有 AppContext 的情况下正常执行此操作,并在 MainForm_Closing、OnFormClosed、App_Exit 或类似事件中进行清理。
1 2 3 4 5 6 7 8 9 10 11 | public class Program { [STAThread] private static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new MyAppContext()); <- no need Application.Run(new MainForm()); } } |
试试看:
1 2 3 4 5 | protected override void OnFormClosed(FormClosedEventArgs e) { base.OnFormClosed(e); Environment.Exit(0); } |
编辑:
这对我来说很好。所以肯定是有其他问题。发布更多代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class Program { private class MyAppContext : ApplicationContext { public MyAppContext() : base(new Form()) { //Exit delegate Application.ApplicationExit += new EventHandler(this.OnApplicationExit); MainForm.Show(); } private void OnApplicationExit(object sender, EventArgs e) { //Cleanup code... } } [STAThread] private static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MyAppContext()); } } |