2016-07-20 4 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; 
     }    
     ...