强制关闭应用程序(.net)

时间:2022-10-06 07:27:40

I'm looking to force my application to shut down, and return an Exit code. Had a look on MSDN and I can see that in WPF the Application has a Shutdown method which takes an error code as a parameter, but there doesn't appear to be one for System.Windows.Forms.Application.

我想强制我的应用程序关闭,并返回退出代码。看看MSDN,我可以看到在WPF中,Application有一个Shutdown方法,它将一个错误代码作为参数,但似乎没有一个用于System.Windows.Forms.Application。

I can see Application.Exit() but not a way to pass back an error code.

我可以看到Application.Exit()但不能回传错误代码。

Does anyone know off-hand if this is possible?

如果有可能,有没有人知道副手?

Thanks

3 个解决方案

#1


13  

You can use System.Environment.Exit(yourExitCode).

您可以使用System.Environment.Exit(yourExitCode)。

#2


2  

set the ExitCode property in the System.Environment class and when exitting. e.g.

在System.Environment类中设置ExitCode属性并在退出时。例如

System.Environment.ExitCode = 1
Application.Exit()

#3


2  

Add a ExitCode property (or something similar) to your form class:

向表单类添加一个ExitCode属性(或类似的东西):

class MyForm : Form {
  public int ExitCode { get; set; }

  void ShutDownWithError(int code) {
    ExitCode = code;
    Close();
  }
}

Somewhere in your code you have:

你的代码中的某个地方你有:

static void Main() {
  // ...
  MyForm form = new MyForm();
  Application.Run(myForm);
}

Change that into:

将其改为:

static void Main() {
  // ...
  MyForm myForm = new MyForm();
  Application.Run(myForm);
  Environment.Exit(myForm.ExitCode);
}

When the ShutdownWithError method is called on your form, you will Close the main form. This will jump out of the loop started with Application.Run. Then you just fetch the exit code and kill the process with Environment.Exit.

在窗体上调用ShutdownWithError方法时,您将关闭主窗体。这将跳出使用Application.Run启动的循环。然后你只需获取退出代码并使用Environment.Exit终止进程。

#1


13  

You can use System.Environment.Exit(yourExitCode).

您可以使用System.Environment.Exit(yourExitCode)。

#2


2  

set the ExitCode property in the System.Environment class and when exitting. e.g.

在System.Environment类中设置ExitCode属性并在退出时。例如

System.Environment.ExitCode = 1
Application.Exit()

#3


2  

Add a ExitCode property (or something similar) to your form class:

向表单类添加一个ExitCode属性(或类似的东西):

class MyForm : Form {
  public int ExitCode { get; set; }

  void ShutDownWithError(int code) {
    ExitCode = code;
    Close();
  }
}

Somewhere in your code you have:

你的代码中的某个地方你有:

static void Main() {
  // ...
  MyForm form = new MyForm();
  Application.Run(myForm);
}

Change that into:

将其改为:

static void Main() {
  // ...
  MyForm myForm = new MyForm();
  Application.Run(myForm);
  Environment.Exit(myForm.ExitCode);
}

When the ShutdownWithError method is called on your form, you will Close the main form. This will jump out of the loop started with Application.Run. Then you just fetch the exit code and kill the process with Environment.Exit.

在窗体上调用ShutdownWithError方法时,您将关闭主窗体。这将跳出使用Application.Run启动的循环。然后你只需获取退出代码并使用Environment.Exit终止进程。