Windows 10关机延迟,VB.NET

时间:2017-01-08 22:29:05

标签: vb.net windows-10

我想延迟 Windows 10关闭,以便我的应用可以完成一些必要的操作,比如保存数据......

以下是一个实现延迟的工作代码示例,但是窗口在等待约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

请提供工作代码(如果这与窗口完全相同)。

由于

2 个答案:

答案 0 :(得分:3)

嗯,你可以做的一件事就是让你的应用程序在完成必要的工作后触发一个关闭命令。

<强>更新

在对此进行调查后,结果发现带有WndProc消息的ENDSESSION方法被多次触发,导致CleanUpAndSave()再次被执行。因此,除了shutdown命令之外,您还需要添加一个布尔值来检查消息是否已从系统发送到您的应用程序。

以下代码经过测试,在 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

但是,我建议您不要暂停关机命令并立即开始做一些工作,而不会向用户发出确认消息,特别是如果该工作需要几分钟< / em>的

相反,您应该在系统关闭之前显示一个消息框,向用户解释应用程序需要做某些工作,并让他们决定是否要做工作或立即关闭。系统将通知用户您的应用程序正在阻止其关闭。如果他们在意,他们会点击&#34;取消&#34;并阅读你的消息。如果他们不在乎,他们可以选择强制关机&#34;无论如何是否显示消息

希望有所帮助:)

答案 1 :(得分:0)