ProgrammingDude ProgrammingDude - 1 year ago 101 Question

Is there any way to pause a Windows shutdown so that a forms.closing method can complete?

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")
_logger.Debug("Hit frmMain_Closing 2")
End If
End Sub

Every time I am logging twice to a log file using the
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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download