12

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.

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

1 Answer 1

16

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

3
  • That will completely stop the computer from shutting down, I'm trying to halt the shutdown until my program is ready to exit. Sorry i should have specified that in the OP.
    – zaza
    Aug 21, 2011 at 5:48
  • I don't really understand... this event itself does nothing... if your code takes long to respond then Windows will ask the user if he wants to kill your application which you can't really prevent... your app should be fast when handling this event.. you could try to tell Windows not to shutdown (setting e.Cancel = true; in the event handler)...
    – Yahia
    Aug 21, 2011 at 5:53
  • ops sry, it was a bit of misunderstanding on my side. i thought i had to cancel the SessionEndingCancelEventArgs event before i could call events in my application. your solution works perfectly.
    – zaza
    Aug 21, 2011 at 6:14

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.