I am trying to put some information in a database when windows begins to shutdown. In my application I am handling the Form.Closing event. However, Windows will go ahead and shut down and my Method doesn't have time to complete. Is there any way to pause the shutdown long enough to handle the shutdown? Here is my method that I am currently using.
Private Sub frmMain_Closing(sender As Object, e As FormClosingEventArgs) Handles Me.Closing
If e.CloseReason = CloseReason.WindowsShutDown Then
_logger.Debug("Hit frmMain_Closing 2")
e.Cancel = True
Sorry for this misformation.
In short, there is no way to delay or cancel a Windows shutdown. It will tap all processes "nicely" to exit, then go through and kill any ones that haven't.
You can delay shutdown until your process finishes. To do this, you need to use
You should be hooking the WM_QUERYENDSESSION message in order to get the opportunity to do something. You'll need to override the WinProc, deal with the message, and then call the base WinProc. Take a look at https://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.sessionending(v=vs.110).aspx (scroll down to remarks.)
Keep in mind that Windows won't wait forever, but this will give you a bit of advance notification.. hopefully enough that you have a chance to do whatever you need to do. Prioritize the important stuff first, in the hopes that it finishes before the process is killed.
Once you've hooked WM_QUERYENDSESSION, you should call
ShutdownBlockReasonCreate() to block shutdown until your app is finished closing. Once finished, call
ShutdownBlockReasonDestroy(). For more information, see this MSDN article (scroll down to "Applications that must block shutdown should use the new shutdown reason API").