如何使Winforms表单终止应用程序?

问题描述:

我在C#中编写Winforms。我想设置我的程序,以便如果表单关闭,程序将终止或停止。我已经知道如何选择首先打开的表单。如何使Winforms表单终止应用程序?

这是我的Program.cs代码:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Windows.Forms; 

namespace MainMenu 
{ 
    static class Program 
    { 
     /// <summary> 
     /// The main entry point for the application. 
     /// </summary> 
     [STAThread] 
     static void Main() 
     { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 
      Application.Run(new Login()); 
     } 
    } 
} 

我想设置我的login.cs形式,使得如果窗体关闭,该程序将终止。这可能吗?

`

要做些什么,当窗体关闭,您需要handle the FormClosing event。在您的事件处理程序中,请致电Application.Exit()来终止该应用程序。

使用上述链接的答案(但在C#)的模型,使用此事件处理程序:

private void Form_Closing(Object sender, FormClosingEventArgs e) 
{ 
    Application.Exit(); 
} 

要添加的处理程序,只需注册方法在你的窗体类的事件本身(基于this来自MSDN的讨论):

this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(Form_Closing);