我已经用c#发布了一个应用程序。每当我通过单击红色退出按钮关闭主表单时,表单都会关闭,但不会关闭整个应用程序。当我试图关闭电脑时,我发现了这一点,随后我添加了大量带有MessageBox警报的子窗口。

我尝试了应用程序。退出,但它仍然调用所有子窗口和警报。我不知道如何使用环境。退出以及要放入哪个整数。

此外,每当我的表单调用FormClosed或FormClosing事件时,我用this.Hide()函数关闭应用程序;这会影响我的应用程序的行为吗?


从MSDN:

应用程序。退出

通知所有消息泵它们必须终止,然后在处理完消息后关闭所有应用程序窗口。如果你已经调用了应用程序,这是要使用的代码。Run (WinForms应用程序),此方法停止所有线程上运行的所有消息循环,并关闭应用程序的所有窗口。

环境。退出

终止此进程并为底层操作系统提供指定的退出码。这是在使用控制台应用程序时调用的代码。

本文,应用。退出vs.环境。退出,指向一个好的提示:

你可以通过检查System.Windows.Forms.Application.Run属性来确定System.Windows.Forms.Application.MessageLoop是否被调用。如果为真,则已经调用了Run,您可以假设WinForms应用程序如下所示正在执行。

if (System.Windows.Forms.Application.MessageLoop) 
{
    // WinForms app
    System.Windows.Forms.Application.Exit();
}
else
{
    // Console app
    System.Environment.Exit(1);
}

为什么要申请。退出失败?


顺便说一下。每当我的窗体调用formclosed或窗体关闭事件时,我就用this.Hide()函数关闭应用程序。这会影响我的应用程序现在的行为吗?

简而言之,是的。当主窗体(窗体通过application启动)结束时,整个应用程序将结束。在Main方法中运行)是关闭的(不是隐藏的)。

If your entire application should always fully terminate whenever your main form is closed then you should just remove that form closed handler. By not canceling that event and just letting them form close when the user closes it you will get your desired behavior. As for all of the other forms, if you don't intend to show that same instance of the form again you just just let them close, rather than preventing closure and hiding them. If you are showing them again, then hiding them may be fine.

If you want to be able to have the user click the "x" for your main form, but have another form stay open and, in effect, become the "new" main form, then it's a bit more complicated. In such a case you will need to just hide your main form rather than closing it, but you'll need to add in some sort of mechanism that will actually close the main form when you really do want your app to end. If this is the situation that you're in then you'll need to add more details to your question describing what types of applications should and should not actually end the program.


我知道这不是你遇到的问题,但是另一个可能发生这种情况的原因是你在应用程序中打开了一个非后台线程。

using System;
using System.Threading;
using System.Windows.Forms;

namespace Sandbox_Form
{
    static class Program
    {
        private static Thread thread;

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            thread = new Thread(BusyWorkThread);
            thread.IsBackground = false;
            thread.Start();

            Application.Run(new Form());

        }

        public static void BusyWorkThread()
        {
            while (true)
            {
                Thread.Sleep(1000);
            }
        }
    }
}

当IsBackground为false时,它将保持程序打开直到线程完成,如果你设置IsBackground为true,线程将不会保持程序打开。像backgroundworker, ThreadPool和Task都在内部使用一个IsBackground设置为true的线程。


在这种情况下,退出应用程序最合适的方法是覆盖App.xaml.cs中的onExit()方法:

protected override void OnExit(ExitEventArgs e) {
    base.OnExit(e); 
}