简体   繁体   English

应用程序自动关闭

[英]Application closes automatically

This code doesn't show the Window, it just closes automatically. 此代码不显示窗口,而是自动关闭。 Why is this happening? 为什么会这样呢?

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var window = new MainWindow();
        window.ShowDialog();
    }
}

I know that you can fix it adding a new Application.Run(window) but I would like to know why it has this behavior and why you have to invoke the Run method over the window instance. 我知道您可以通过添加一个新的Application.Run(window)来修复它,但是我想知道为什么它具有这种行为以及为什么必须在窗口实例上调用Run方法。

EDIT: 编辑:

Extending the previous question, I've noticed that this code will work: 扩展上一个问题,我注意到此代码将起作用:

  1. Create a new WPF Application. 创建一个新的WPF应用程序。
  2. Go to App.xaml and delete the StartupUri 转到App.xaml并删除StartupUri
  3. Modify the App.xaml.cs overriding the method OnStartup 修改App.xaml.cs以覆盖方法OnStartup

     public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var window = new MainWindow(); window.Show(); } } 

With this, the window remains open. 这样,窗口将保持打开状态。 What's going on under the hood? 到底是怎么回事?

Microsoft Windows programs are event-based. Microsoft Windows程序是基于事件的。 They act upon messages that the operating system posts to the main thread of the application. 它们根据操作系统发布到应用程序主线程的消息进行操作。 These messages are received from the message queue by the application by repeatedly calling the GetMessage (or PeekMessage) function in a section of code called the "event loop." 应用程序通过在称为“事件循环”的代码部分中重复调用GetMessage(或PeekMessage)函数,从消息队列接收这些消息。

When Run is called, Application attaches a new Dispatcher instance to the UI thread. 调用Run时,Application将新的Dispatcher实例附加到UI线程。 Next, the Dispatcher object's Run method is called, which starts a message loop to process windows messages. 接下来,调用Dispatcher对象的Run方法,该方法启动消息循环以处理Windows消息。 Finally, the Dispatcher object calls the Application object's OnStartup method to raise the Startup event. 最后,Dispatcher对象调用Application对象的OnStartup方法引发Startup事件。

Without a message loop, the application is unable to support the UI. 没有消息循环,该应用程序将无法支持UI。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM