2014-03-05 61 views
1

我试图用下面的代码显示一个winform,但它打开并立即关闭。 我无法理解这个原因。任何想法?为什么不在没有Application.Run()的情况下打开winform?

[STAThread] 
    static void Main() 
    { 
     try 
     { 
      AppDomain.CurrentDomain.UnhandledException += AllUnhandledExceptions; 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 
      Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); 

      Test testWin = new Test(); 
      testWin.Show(); 
     } 
     catch (Exception ex) 
     { 
      Logger.Error("Main : " + ex.Message, typeof(Program)); 
     } 
    } 

它的工作正常,如果我用Application.Run(testWin)替换testWind.Show()。

+4

它“打开”很好,只有在程序终止一微秒后才能看到它。 Application.Run()是GUI应用程序中的一个硬性要求,它解决了[生产者 - 消费者问题](http://en.wikipedia.org/wiki/Producer-consumer_problem)。制作人是操作系统,消费者是你的UI。你不消费任何东西。 –

回答

2

Application.Run运行基本上处理UI事件等的消息循环,直到所有可见窗口关闭。该方法阻塞,直到消息循环关闭。

你需要运行这个消息循环才能保持UI基本不变 - 而Show()只会显示窗口,但不会运行任何类型的消息循环本身,也不会阻止 - Main方法完成,并且应用程序终止。

1

您应该使用ShowDialog方法。

Test testWin = new Test(); 
testWin.ShowDialog(); 
+0

展会有什么问题? – armin

+1

它实际上正在工作,但它立即打开和关闭 –

相关问题