简体   繁体   中英

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.

EDIT:

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

  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 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."

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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