问题
Is it possible in .NET to ascertain whether my application is closing due to Windows being given a shutdown command (as opposed to any old application closing) in order to either write out some temporary cache files or even block the shutdown long enough to prompt for user input?
Whilst my current scope involves a Winform app and a windows service, I am interested in understanding this in a generic way if possible
回答1:
SystemEvents.SessionEnding looks like a good starting point for you. That article talks about the event sequence involved when a logout/shutdown is occurring.
回答2:
In general, you will want to handle the WM_QUERYENDSESSION Windows message. This will give your application a chance to do cleanup, or to block the shutdown if it's really necessary.
回答3:
Handle the SessionEnded event on the Microsoft.Win32.SystemEvents type.
来源:https://stackoverflow.com/questions/245111/ascertaining-a-shutdown-is-closing-my-application