VB.NET - Detecting when the computer wakes up.

Marc Menzel 101 Reputation points
2024-10-15T21:38:54.6833333+00:00

I have tried a suggestion that someone posted on Stack Overflow, however, it is not working. I can't seem to find the solution online. I wonder if it is even possible to detect when the computer wakes up from sleep in VB.NET. Heer is my code.

First, I put the AddHandler statement in the Form Load event.

AddHandler Microsoft.Win32.SystemEvents.PowerModeChanged, AddressOf SystemEvents_PowerModeChanged

Then I put the following Code in a sub routine.

`Private Sub SystemEvents_PowerModeChanged(ByVal sender As Object, ByVal e As PowerModeChangedEventArgs) ' Handles SystemEvents.PowerModeChanged

Select Case e.Mode

Case PowerModes.Resume

UpdateEventBellScheduleInformation()

Case PowerModes.StatusChange

Case PowerModes.Suspend

End Select

End Sub

I don't know what I am missing.

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,944 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,743 questions
{count} votes

Accepted answer
  1. Q&A Assist
    2024-10-15T21:38:54.69+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    To detect when the computer wakes up from sleep in VB.NET, your approach using the SystemEvents.PowerModeChanged event is correct. The code you provided should work as intended, but here are a few things to check:

    1. Ensure the Application is Running: Make sure that your application is running and not minimized or in the background when the wake event occurs.
    2. Event Subscription: Verify that the AddHandler statement is indeed being executed. You can add a breakpoint or a debug message to confirm that the event is being subscribed to properly.
    3. PowerMode Enumeration: Ensure that you are handling the PowerModes.Resume case correctly. This is where you should place the logic that needs to execute when the system resumes.
    4. Dispose of Event Handlers: If your application closes or the form is disposed, ensure that you remove the event handler to prevent memory leaks.
    5. Permissions: Sometimes, certain permissions or settings in the operating system may affect the ability to receive power mode change notifications.

    If everything appears to be set up correctly and it still doesn't work, consider testing on a different machine or environment to rule out system-specific issues.


    References:

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Jiachen Li-MSFT 32,451 Reputation points Microsoft Vendor
    2024-10-16T07:01:40.9766667+00:00

    Hi @Marc Menzel ,

    You can use the Windows API to detect wake-up events more directly.

    Listen for the WM_POWERBROADCAST message using WndProc in your form. PBT_APMRESUMESUSPEND is sent when the system resumes from sleep.

    Protected Overrides Sub WndProc(ByRef m As Message)
        Const WM_POWERBROADCAST As Integer = &H218
        Const PBT_APMRESUMESUSPEND As Integer = &H7
    
        If m.Msg = WM_POWERBROADCAST Then
            If m.WParam.ToInt32() = PBT_APMRESUMESUSPEND Then
                UpdateEventBellScheduleInformation()
            End If
        End If
        MyBase.WndProc(m)
    End Sub
    

    Best Regards.

    Jiachen Li


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Castorix31 86,046 Reputation points
    2024-10-16T10:28:19.87+00:00

    Some people said WM_POWERBROADCAST is not always received (WinUI 3 thread : https://github.com/microsoft/WindowsAppSDK/discussions/2630)

    This test that I converted from C# works on my Windows 10 OS :

    Imports System.Runtime.InteropServices
    
    Public Class Form1
    
        Public Delegate Function DEVICE_NOTIFY_CALLBACK_ROUTINE(ByVal Context As IntPtr, ByVal Type As UInteger, ByVal Setting As IntPtr) As UInteger
    
        <StructLayout(LayoutKind.Sequential)>
        Public Structure DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS
            Public Callback As DEVICE_NOTIFY_CALLBACK_ROUTINE
            Public Context As IntPtr
        End Structure
    
        <DllImport("Powrprof.dll", SetLastError:=True, CharSet:=CharSet.Unicode)>
        Public Shared Function PowerRegisterSuspendResumeNotification(Flags As UInteger, Recipient As IntPtr, ByRef RegistrationHandle As IntPtr) As UInteger
        End Function
    
        Public Const DEVICE_NOTIFY_CALLBACK As Integer = 2
    
        Public Const PBT_APMQUERYSUSPEND = &H0
        Public Const PBT_APMQUERYSTANDBY = &H1
        Public Const PBT_APMQUERYSUSPENDFAILED = &H2
        Public Const PBT_APMQUERYSTANDBYFAILED = &H3
        Public Const PBT_APMSUSPEND = &H4
        Public Const PBT_APMSTANDBY = &H5
        Public Const PBT_APMRESUMECRITICAL = &H6
        Public Const PBT_APMRESUMESUSPEND = &H7
        Public Const PBT_APMRESUMESTANDBY = &H8
        Public Const PBTF_APMRESUMEFROMFAILURE = &H1
        Public Const PBT_APMBATTERYLOW = &H9
        Public Const PBT_APMPOWERSTATUSCHANGE = &HA
        Public Const PBT_APMOEMEVENT = &HB
        Public Const PBT_APMRESUMEAUTOMATIC = &H12
        Public Const PBT_POWERSETTINGCHANGE = &H8013
    
        Private callbackDelegate As DEVICE_NOTIFY_CALLBACK_ROUTINE
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            callbackDelegate = New DEVICE_NOTIFY_CALLBACK_ROUTINE(AddressOf DeviceNotifyCallbackRoutine)
            Dim dnsp As New DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS()
            dnsp.Callback = callbackDelegate
            Dim pDeviceNotify As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(dnsp))
            Marshal.StructureToPtr(dnsp, pDeviceNotify, False)
            Dim pRegistrationHandle As IntPtr = IntPtr.Zero
            Dim nRet As UInteger = PowerRegisterSuspendResumeNotification(DEVICE_NOTIFY_CALLBACK, pDeviceNotify, pRegistrationHandle)
            Marshal.FreeHGlobal(pDeviceNotify)
        End Sub
    
        Private Shared Function DeviceNotifyCallbackRoutine(ByVal Context As IntPtr, ByVal Type As UInteger, ByVal Setting As IntPtr) As UInteger
            Console.Beep(5000, 10)
            ' PBT_APMSUSPEND, PBT_APMRESUMESUSPEND, PBT_APMRESUMEAUTOMATIC
            System.Diagnostics.Debug.WriteLine(String.Format("DeviceNotify - Type = 0x{0:X4}", Type))
            Return 0
        End Function
    End Class
    
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.