【问题标题】:What's the proper way to exit the application from WindowsFormsApplicationBase.OnCreateMainForm()?从 WindowsFormsApplicationBase.OnCreateMainForm() 退出应用程序的正确方法是什么?
【发布时间】:2016-11-23 02:18:43
【问题描述】:

假设在WindowsFormsApplicationBase.OnCreateMainForm() 的时候出了点问题,我该如何“温和地”退出应用程序?我想退出就像使用按下关闭按钮一样,所以我猜Environment.Exit() 不太适合,因为它会立即终止应用程序并且可能不允许应用程序自行清理。

我的代码如下所示:

 public class MyApp : WindowsFormsApplicationBase
    {
        public MyApp()
        {
            this.IsSingleInstance = true;
        }

        protected override void OnCreateSplashScreen()
        {
            this.SplashScreen = new splashForm();
        }

        protected override void OnCreateMainForm()
        {
          if(!do_something()) {
            /* something got wrong, how do I exit application here? */
          }

          this.MainForm = new Form1(arg);
        }

还有我的Main() 函数:

[STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            new MyApp().Run(args);
         }

【问题讨论】:

  • 应用程序尚未启动。它仍然只是初始化,Application.Run() 调用稍后发生。所以 Application.Exit() 不能工作。当然,Environment.Exit() 会轻松完成工作。
  • Environment.Exit() 将退出而不是杀死应用程序?如果是这样,我想这是要走的路

标签: c# .net winforms error-handling splash-screen


【解决方案1】:

只需使用return:

protected override void OnCreateMainForm()
{
    if(!do_something())
    {
        return;
    }

    // This won't be executed if '!do_something()' is true.
    this.MainForm = new Form1(arg);
}

这将退出当前线程,因此不会设置MainForm 属性。

【讨论】:

  • 这不正常存在,抛出 NoStartupFormException。
  • 感谢您更新它@axk。
【解决方案2】:

我通过创建一个空表单来解决这个问题,该表单在加载事件处理程序中立即关闭。这样可以避免NoStartupFormException

    public partial class SelfClosingForm : Form
    {
        public SelfClosingForm()
        {
            InitializeComponent();
        }

        private void SelfClosingForm_Load(object sender, EventArgs e)
        {
            Close();
        }
    }

    protected override void OnCreateMainForm()
    {
        ...

        if (error)
        {
            //this is need to avoid the app hard crashing with NoStartupFormException
            this.MainForm = new SelfClosingForm();
            return;
        }               
        ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 2016-11-12
    • 2019-09-08
    相关资源
    最近更新 更多