关闭从App.xaml.cs的WPF应用程序

问题描述:

我目前正在写一个WPF应用程序,它做的命令行参数在App.xaml.cs(因为启动事件似乎是在这些参数获得的推荐方法是必要的)处理。基于我想在这一点上已经退出程序的论点,因为据我所知,应该在WPF与 Application.Current.Shutdown()或完成这种情况下(如我在当前的应​​用程序对象)可能也只是 this.Shutdown()

I am currently writing a WPF application which does command-line argument handling in App.xaml.cs (which is necessary because the Startup event seems to be the recommended way of getting at those arguments). Based on the arguments I want to exit the program at that point already which, as far as I know, should be done in WPF with Application.Current.Shutdown() or in this case (as I am in the current application object) probably also just this.Shutdown().

唯一的问题是,这似乎并没有工作的权利。我与关机后,调试器和代码通过踩()行仍然被执行为后来导致错误的方法,因为我所期望的应用程序不活了长。同时主窗口仍然(在XAML中的StartupUri属性声明)被载入。

The only problem is that this doesn't seem to work right. I've stepped through with the debugger and code after the Shutdown() line still gets executed which leads to errors afterwards in the method, since I expected the application not to live that long. Also the main window (declared in the StartupUri attribute in XAML) still gets loaded.

我检查该方法的文档,没有发现任何在告诉我的言论我不应该在所有中 Application.Startup 应用使用它。

I've checked the documentation of that method and found nothing in the remarks that tell me that I shouldn't use it during Application.Startup or Application at all.

那么,是什么在这一点退出程序的正确方法,我。即在应用程序的启动事件处理程序对象?

So, what is the right way to exit the program at that point, i. e. the Startup event handler in an Application object?

首先从App.xaml中删除StartupUri属性,然后使用以下内容:

First remove the StartupUri property from App.xaml and then use the following:

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        bool doShutDown = ...;

        if (doShutDown)
        {
            Shutdown(1);
            return;
        }
        else
        {
            this.StartupUri = new Uri("Window1.xaml", UriKind.Relative);
        }
    }