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

发布于 2024-07-08 04:18:14 字数 214 浏览 4 评论 0原文

我希望强制关闭我的应用程序,并返回退出代码。 查阅了 MSDN,我发现在 WPF 中,应用程序有一个 Shutdown 方法,该方法将错误代码作为参数,但似乎没有针对 System.Windows.Forms.Application 的方法。

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

有谁知道这是否可能?

谢谢

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.

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

Does anyone know off-hand if this is possible?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

软糖 2024-07-15 04:18:14

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

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

↘紸啶 2024-07-15 04:18:14

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

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

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

System.Environment.ExitCode = 1
Application.Exit()
别闹i 2024-07-15 04:18:14

将 ExitCode 属性(或类似的属性)添加到表单类中:

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

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

在代码中的某个位置:

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

将其更改为:

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

当在表单上调用 ShutdownWithError 方法时,您将关闭主表单。 这将跳出以 Application.Run 开始的循环。 然后,您只需获取退出代码并使用Environment.Exit 终止进程即可。

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文