Reputation: 597
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_Closing1")
NewEvent(Events.SystemShutdownNormal)
System.Threading.Thread.Sleep(10000)
_logger.Debug("Hit frmMain_Closing 2")
End If
End Sub
Every time I am logging twice to a log file using the _logger.Debug("Hit...")
However, only the first time I call it is getting written to the file. I have tried the method of setting e.Cancel = True
, but that didn't seem to work.
Upvotes: 1
Views: 288
Reputation: 13357
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 ShutdownBlockReasonCreate()
.
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").
The PInvoke declares can be found here and here.
Upvotes: 2