我想延迟 Windows 10 关闭,以便我的应用程序可以完成一些必要的操作,例如保存数据...
以下是实现延迟的工作代码示例,但是 Windows 在等待大约 1 分钟后取消关闭。
如何实现延迟而不让 Windows 一分钟后中止关闭? (我的应用程序可能需要 2 或 4 分钟才能完成)
Public Class Form1
Declare Function ShutdownBlockReasonCreate Lib "user32.dll" (ByVal hWnd As IntPtr, <Runtime.InteropServices.MarshalAs(Runtime.InteropServices.UnmanagedType.LPWStr)> ByVal reason As String) As Boolean
Declare Function ShutdownBlockReasonDestroy Lib "user32.dll" (ByVal hWnd As IntPtr) 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
' Block shutdown
ShutdownBlockReasonCreate(Me.Handle, "Testing 123...")
' Do work
CleanUpAndSave()
' Continue with shutdown
ShutdownBlockReasonDestroy(Me.Handle)
Return
End If
MyBase.WndProc(aMessage)
End Sub
Private Sub CleanUpAndSave()
Dim sw As New Stopwatch
' Pretend work for 3 minutes
sw.Start()
Do While sw.ElapsedMilliseconds < 180000
Application.DoEvents()
Loop
sw.Stop()
End Sub
请提供工作代码(如果 Windows 可以实现)。
谢谢
最佳答案
好吧,您可以做的一件事是让您的应用程序在完成必要的工作后触发关闭命令。
更新:
经过调查后,发现带有 ENDSESSION
消息的 WndProc
方法被多次触发,导致 CleanUpAndSave()
也被触发再次进行。因此,除了 shutdown 命令之外,您还需要添加一个 bool 值来检查消息是否已从系统发送到您的应用程序。
以下代码经过测试,在 Windows 7 和 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
但是,我建议您不要暂停关闭命令并立即开始执行某些工作,而不向用户提示确认消息尤其是当该工作需要几分钟时.
相反,您应该显示一个消息框,向用户解释应用程序需要在系统关闭之前执行一些工作,并让他们决定是否执行该工作或立即关闭。系统将通知用户您的应用程序正在阻止其关闭。如果他们关心,他们会点击“取消”并阅读您的消息。如果他们不在乎,无论您是否显示该消息,他们都可以选择“强制关闭”。
希望有帮助:)
关于vb.net - Windows 10 关闭延迟,VB.NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41538592/