【问题标题】:How can I make a Winforms form terminate the application?如何让 Winforms 表单终止应用程序?
【发布时间】:2017-10-09 03:02:31
【问题描述】:

我正在用 C# 编写 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 表单,以便如果该表单关闭,程序将终止。这可能吗?

`

【问题讨论】:

    标签: c# .net winforms terminate


    【解决方案1】:

    要在表单关闭时执行某些操作,您需要handle the FormClosing event。在您的事件处理程序中,调用 Application.Exit() 以终止应用程序。

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

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

    要添加处理程序,只需在表单类中将方法注册到事件中(基于来自 MSDN 的this 讨论):

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

    【讨论】:

      猜你喜欢
      • 2011-06-28
      • 2010-10-05
      • 1970-01-01
      • 2015-05-29
      • 2023-04-03
      • 1970-01-01
      • 2019-08-05
      • 2011-08-29
      相关资源
      最近更新 更多