应用自动关闭 [英] Application closes automatically

查看:164
本文介绍了应用自动关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这code没有显示窗口,它只是自动关闭。为什么会出现这种情况?

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();
    }
}

我知道,你可以修复它​​加入了新的 Application.Run(窗口),但我想知道为什么有这种行为,你为什么要调用Run方法在窗口实例。

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.

编辑:

扩展previous的问题,我注意到,这code将工作:

Extending the previous question, I've noticed that this code will work:

  1. 创建一个新的WPF应用程序。
  2. 转到的App.xaml和删除的StartupUri
  3. 修改App.xaml.cs覆盖方法OnStartup

  1. Create a new WPF Application.
  2. Go to App.xaml and delete the StartupUri
  3. Modify the App.xaml.cs overriding the method 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程序都是基于事件的。他们的行为在消息操作系统岗位到应用程序的主线程。这些消息从消息队列应用程序接收到通过反复调用的GetMessage(或的PeekMessage)在code一款功能称为事件循环。

Microsoft Windows programs are event-based. 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."

当运行被调用时,应用程序附加一个新的调度程序实例UI线程。下一步,分派对象的run方法被调用,以启动一个消息循环来处理窗口消息。最后,调度对象调用应用程序对象的OnStartup方法,以提高启动事件。

When Run is called, Application attaches a new Dispatcher instance to the UI thread. Next, the Dispatcher object's Run method is called, which starts a message loop to process windows messages. Finally, the Dispatcher object calls the Application object's OnStartup method to raise the Startup event.

如果没有消息循环,应用程序无法支持用户界面。

Without a message loop, the application is unable to support the UI.

这篇关于应用自动关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆