I want to delay windows 10 from shutting down so that my app can finish up some necessary actions like saving data...
Following is a working code example to ach
Well, one thing you can do is to make your application trigger a shutdown command after finishing the necessary work.
Update:
After investigating this, turns out that the WndProc
method with ENDSESSION
message gets triggered more than once, causing CleanUpAndSave()
to also be carried out again. Hence, in addition to the shutdown command, you'll need to add a boolean to check if the message has already been sent from the system to your application.
The following code was tested and it works just fine on both Windows 7 and windows 10:
Private ShutdownDelayed As Boolean
Protected Overrides Sub WndProc(ByRef aMessage As Message)
Const WM_QUERYENDSESSION As Integer = &H11
Const WM_ENDSESSION As Integer = &H16
If aMessage.Msg = WM_QUERYENDSESSION OrElse aMessage.Msg = WM_ENDSESSION Then
' Check if the message was sent before and the shutdown command is delayed.
If ShutdownDelayed Then Exit Sub
' Block shutdown
ShutdownBlockReasonCreate(Me.Handle, "Testing 123...")
ShutdownDelayed = True
' Do work
CleanUpAndSave()
' Continue with shutdown
ShutdownBlockReasonDestroy(Me.Handle)
' Do shutdown
Dim p As New ProcessStartInfo("shutdown", "/s /t 0")
p.CreateNoWindow = True
p.UseShellExecute = False
Process.Start(p)
' Exit the application to allow shutdown (For some reason 'ShutdownBlockReasonDestroy'
' doesn't really unblock the shutdown command).
Application.Exit()
Return
End If
MyBase.WndProc(aMessage)
End Sub
However, I suggest that you don't suspend the shutdown command and start doing some work immediately without prompting a confirmation message to the user especially if that work takes several minutes.
Instead, you should display a message box explaining to the user that the application needs to do some work before the system shuts down, and let them decide whether to do that work or to shut down immediately. The system will inform the user that your application is preventing it from shutting down. If they care, they will click "Cancel" and read your message. If they don't care, they'll have the option to "Force shutdown" anyway whether you displayed the message or not.
Hope that helps :)
You cannot suspend windows shutdown for more than a few seconds: https://blogs.msdn.microsoft.com/oldnewthing/20060216-06/?p=32263