2016-07-20 22 views
1

WindowsFormsApplicationBase.OnCreateMainForm()の時に何か問題があったとしましょう。アプリケーションから「やさしく」どのように終了しますか?私は終了ボタンを使用したように終了したいので、すぐにアプリケーションを終了し、アプリケーション自体をクリーンアップできない可能性があるので、Environment.Exit()はうまく収まらないと思います。WindowsFormsApplicationBase.OnCreateMainForm()からアプリケーションを終了する適切な方法は何ですか?

私のコードを次のようになります。

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); 
     } 
+0

アプリケーションはまだ開始していません。まだ初期化中であり、Application.Run()呼び出しは後で発生します。したがって、Application.Exit()は機能しません。確かに、Environment.Exit()は簡単に仕事を終わらせます。 –

+0

Environment.Exit()は終了するのではなく、アプリケーションを終了しますか?もしそうなら、それは行く方法だと思います。 – Jack

答えて

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プロパティは設定されません。

+0

これは正常に存在せず、NoStartupFormExceptionがスローされます。 – axk

+0

@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; 
     }    
     ... 
関連する問題