Catch windows shutdown event in a wpf application
Asked Answered
D

1

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

Deerhound answered 21/8, 2011 at 5:28 Comment(0)
Z
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...

Zamir answered 21/8, 2011 at 5:37 Comment(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.Deerhound
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)...Zamir
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.Deerhound

© 2022 - 2024 — McMap. All rights reserved.