如何以编程方式退出或关闭 UWP 应用程序? (Windows 10)

How to exit or close an UWP app programmatically? (Windows 10)

我需要它作为自己的退出按钮。请告诉我? 我试试这个: this.Close(); //或退出不工作(

这是退出 UWP 应用程序的受支持方式:

Application.Current.Exit();

然而,您应该使用它的情况相对较少。仔细考虑与使用此方法的场景相关的 UI 经验。例如,如果某些帐户已过期或远程管理的安全权限被撤销,则以编程方式退出应用程序可能是合理的。在不违反 Windows 准则的情况下,您很少有自己的 "Exit" 按钮位于屏幕中间。

可以使用CoreApplicationclass。它提供了一个 static exit method:

public void CloseApp()
{
    CoreApplication.Exit();
}

但是,文档说明如下:

Note Do not use this method to shut down an app outside of testing or debugging scenarios.

遗憾的是,其背后的原因不为人知。


此外,您可以使用老式的 Application.Exit 方法(非静态):

public void CloseApp()
{
    Application.Current.Exit();
}

这里的备注你也要看看:

Use this method to provide UI that enables users to exit your app. Normally, however, you should not provide this UI because the system automatically manages app lifetime and terminates suspended apps as needed to free resources.

tl;博士: Exit 两种方法都将终止应用程序,而不是暂停它。你应该问问自己,这是否真的是你想要做的。

如果您想暂停应用程序而不是终止应用程序,请尝试使用 ApplicationView.TryConsolidateAsync()。例如,如果应用仅实现一个 ApplicationView 尝试调用 ApplicationView.GetForCurrentView().TryConsolidateAsync() 关闭应用。

这种方法的明显好处是应用程序关闭就像您在标题栏中按下关闭按钮一样,关闭是优雅的,动画是相同的,应用程序是暂停而不是突然退出。

此外,当您在通过此方法关闭后再次启动您的应用程序时,应用程序将以与您之前关闭应用程序时相同的位置和大小启动,而使用 Application.Current.Exit()CoreApplication.Exit() 不会启动相同位置和大小的应用程序。