如何正确退出 C# 应用程序? [英] How to properly exit a C# application?

查看:29
本文介绍了如何正确退出 C# 应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个已发布的 C# 应用程序.这里的问题是每当我通过单击红色退出按钮关闭主窗体时,它会关闭窗体但不会关闭应用程序.我在尝试关闭计算机时发现了这一点,希望我制作的应用程序运行顺利,然后我被许多子窗口轰炸,我已经放置了 MessageBox 警报.

我尝试了 Application.Exit 但它仍然调用所有子窗口和警报,我不知道如何使用 Environment.Exit 以及要放入哪个整数

顺便说一句,每当我的表单调用 formclosedform closed 事件时,我都会使用 this.Hide() 函数关闭应用程序;这会影响我的应用程序现在的行为方式吗?

解决方案

来自 MSDN:

应用程序退出<块引用>

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

Environment.Exit

<块引用>

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

本文,Application.Exit 与 Environment.Exit,指向一个很好的提示:

您可以通过检查 System.Windows.Forms.Application.MessageLoop 属性来确定是否已调用 System.Windows.Forms.Application.Run.如果为 true,则 Run 已被调用,您可以假设 WinForms 应用程序按如下方式执行.

if (System.Windows.Forms.Application.MessageLoop){//WinForms 应用程序System.Windows.Forms.Application.Exit();}别的{//控制台应用System.Environment.Exit(1);}

参考:为什么 Application.Exit 会失败?

I have a published application in C#. The problem here is whenever I close the main form by clicking on the red exit button, it closes the form but it doesn't close the application. I found this out when I tried shutting down the computer, hopeful that the application I made was running smoothly then I was bombarded by a lot of child windows with which I have put MessageBox Alerts.

I tried Application.Exit but it still calls all the child windows and alerts and I don't know how to use Environment.Exit and which integer to put into it.

By the way, whenever my forms call the formclosed or form closing event I close the application with a this.Hide() function; Does that affect how my application is behaving now?

解决方案

From MSDN:

Application.Exit

Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This is the code to use if you are have called Application.Run (WinForms applications), this method stops all running message loops on all threads and closes all windows of the application.

Environment.Exit

Terminates this process and gives the underlying operating system the specified exit code. This is the code to call when you are using console application.

This article, Application.Exit vs. Environment.Exit, points towards a good tip:

You can determine if System.Windows.Forms.Application.Run has been called by checking the System.Windows.Forms.Application.MessageLoop property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.

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

Reference: Why would Application.Exit fail to work?

这篇关于如何正确退出 C# 应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆