如何在 C# 中退出 Windows 窗体应用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15649025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:28:14  来源:igfitidea点击:

How to exit a Windows Forms Application in C#

c#

提问by SIMEL

I'm writing a Windows Forms Application in C# that uses only one form. When I want to exit and close the application, I add the code

我正在用 C# 编写一个仅使用一种形式的 Windows 窗体应用程序。当我想退出并关闭应用程序时,我添加了代码

private void Defeat()
{
    MessageBox.Show("Goodbye");
    this.Close();
}

to the class Form1 : Form, which is the form class that was automatically created by Visual Studio. But when this code runs, I get the following message:

到 class Form1 : Form,它是由 Visual Studio 自动创建的表单类。但是当此代码运行时,我收到以下消息:

An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll

Additional information: A generic error occurred in GDI+.

System.Drawing.dll 中发生类型为“System.Runtime.InteropServices.ExternalException”的未处理异常

附加信息:GDI+ 中出现一般错误。

A picture of the message:

留言图片:

Error message

错误信息

What is the problem?

问题是什么?

How should I exit my application?

我应该如何退出我的应用程序?

采纳答案by bizzehdee

You first need to quote your string so the message box knows what to do, and then you should exit your application by telling the application context to exit.

您首先需要引用您的字符串,以便消息框知道要做什么,然后您应该通过告诉应用程序上下文退出来退出您的应用程序。

private void Defeat()
{
    MessageBox.Show("Goodbye");
    Application.Exit();
}

回答by emmerzun

private void btnExit_Click(object sender, EventArgs e)
{
  this.Close();  //”this” refers to the form
}

回答by Dhanasekaran

If you want to close the application, please try this:

如果您想关闭应用程序,请尝试以下操作:

    DialogResult dialog = new DialogResult();

    dialog = MessageBox.Show("Do you want to close?", "Alert!", MessageBoxButtons.YesNo);

    if (dialog == DialogResult.Yes)
    {
        System.Environment.Exit(1);
    }