通用 Windows 程序没有应用程序的关闭事件。本身打算在程序关闭的时候保存偏好设定,看来这么做是没戏了。查阅 MSDN 文档,了解了程序的生命周期。
通用 Windows 程序的生命周期如下:
- 启动,会触发 Launched 事件。
- 正在运行
- 当程序置于后台(PC:最小化程序或平板模式下切换至另外的程序。移动设备及XBOX:切换至另外程序),几秒内没有切换回来时,会进入挂起状态,即 Suspended。此时程序扔驻留在内存中。
- 当系统资源不足时,Windows 会关闭程序。程序被关闭时不会收到通知,因而也没有关闭事件。
- 程序也可以又用户手动关闭。
最佳保存偏好设定的时机有两个,第一是设定被更改的时候,第二就是程序被挂起的时候。
因为当用户手动关闭程序时,不会触发挂起事件,因此偏好设定在更改的时候,就应该进行保存。
在程序进入挂起状态的时候,除了保存偏好设定,也应该将程序的运行状态缓存至磁盘上,因为挂起后,程序就有可能会被系统关闭,或被用户关闭。
相应的,在程序启动时,应该根据上次的执行情况来进行状态的还原。在 App.Xaml 的逻辑代码文件中(App.Xaml.vb / App.Xaml.cs),IDE 已经自动生成了一部分的代码。通过在 OnLaunched
事件方法中,使用 e.PreviousExecutionState
即可对应各种上次执行的状态进行缓存还原或偏好设定的载入。
前次的执行状态有这么几种:
- Terminated,已终止:程序挂起后因系统资源不足而被结束。
- Suspended,已挂起:程序置入后台后几秒内未被切换至前台。此时程序仍驻留在 RAM 内。
- ClosedByUser,由用户手动关闭。
- NotRunning,未运行:自上次机器启动后还未启动过程序。
- Running,运行中:应用程序运行中且处在前台。
以下是示例代码:
' Application was suspended and been terminated by system due to lack of RAM. If e.PreviousExecutionState = ApplicationExecutionState.Terminated Then Util.LoadSettings() End If ' Application was suspended and still stays in the RAM. If e.PreviousExecutionState = ApplicationExecutionState.Suspended Then Util.LoadSettings() End If ' Application was closed by user. If e.PreviousExecutionState = ApplicationExecutionState.ClosedByUser Then Util.LoadSettings() End If ' Application has not ever launched since last boot. If e.PreviousExecutionState = ApplicationExecutionState.NotRunning Then Util.LoadSettings() End If