在WPF应用程序中捕获Windows关闭事件

在WPF应用程序中捕获Windows关闭事件

问题描述:

我有一个c#WPF应用程序,该应用程序在关闭时需要保存数据.如果用户关闭程序,则窗口关闭/关闭"事件可以正常工作,但是如果用户注销/关闭计算机,则不会被调用.

I have a c# WPF application that needs to save data when it closes. The Window Closing/Closed events work fine if the user closes the program, but they do not get called if the user logs off/shutdown the computer.

我已经找到了在winforms程序中捕获此事件的方法(此处,和此处).但我不知道如何在WPF应用程序中实现这一目标.

I have found ways to catch this event in winforms programs (here, and here). but i cant figure out how to achieve this in a WPF application.

我正试图停止关机,直到我的程序准备退出

I'm trying to halt the shutdown until my program is ready to exit

有一个内置事件

There is a built-in event Application.SessionEnding - this event fires when the user logs off or shuts down the computer... you just need to subscribe to that and put your code to save date etc. in there...