从WindowsFormsApplicationBase.OnCreateMainForm()退出应用程序的正确方法是什么?

时间:2016-07-20 02:08:48

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

让我们假设在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);
         }

2 个答案:

答案 0 :(得分:2)

我通过创建一个空表单来解决这个问题,该表单在load事件处理程序中立即关闭。这样可以避免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;
        }               
        ...

答案 1 :(得分:0)

只需使用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属性。