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

3

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

这是我程序中的代码:

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表单,这样如果该表单被关闭,程序将终止。这种情况是否可能发生?
1个回答

1
为了在表单关闭时执行某些操作,您需要处理FormClosing事件。在事件处理程序中,调用Application.Exit()来终止应用程序。
使用上面链接答案中的模型(但使用C#),请使用此事件处理程序:
private void Form_Closing(Object sender, FormClosingEventArgs e)
{
    Application.Exit();
}

要添加处理程序,只需在您的表单类中将该方法注册到事件中,如下所示(基于MSDN this讨论):
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(Form_Closing);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接