Search code examples
c#windows-8windows-runtimelifecycle

How to detect when Windows 8 goes to sleep or resumes


I have an app that keeps a connection alive to a server, however if the user walks away and the tablet goes to sleep, I would like to handle the disconnect gracefully, and I would also like to log back in when the user wakes the tablet.

I've tried in my putting the following code in my connection class, but they never get fired.

Application.Current.Suspending += this.OnAppSuspending;
Application.Current.Resuming += this.OnAppResuming;;

Solution

  • For desktop apps, you can use SystemEvents.PowerModeChanged event to know if Windows is going into sleep state. I don't know if this works for the tablets too, but you can try it...

    From MSDN:

    • Resume The operating system is about to resume from a suspended state.

    • StatusChange A power mode status notification event has been raised by the operating system. This might indicate a weak or charging battery, a transition between AC power and battery, or another change in the status of the system power supply.

    • Suspend The operating system is about to be suspended.

    SystemEvents.PowerModeChanged += OnPowerChange;
    
    private void OnPowerChange(object s, PowerModeChangedEventArgs e) 
    {
        switch ( e.Mode ) 
        {
            case PowerModes.Resume: 
            break;
            case PowerModes.Suspend:
            break;
        }
    }