How to stop a timer during hibernate/ sleep mode in C# winform application?
Asked Answered
S

1

9

I have an application which does a specific task after some time (controlled by a timer). But whenever I start PC after hibernate that application runs. This means that timer keeps running during hibernation for atleast one tick. How can I avoid this.

Surovy answered 1/1, 2011 at 13:30 Comment(1)
Just to get this right, the timer is within the (c#?) application you wrote. You start your application, which starts the timer. You then put your pc (assuming windows os) to sleep/hibernate. After a time period longer than your timer, you restart your computer and the application tick event occured. Now you want to know, how to prevent the timer from 'ticking', while your pc is hibernating. Correct?Tetrapod
C
18

You can handle the SystemEvents.PowerModeChanged event to stop the timer when the machine is suspending and start it again when it is resuming.

 SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;

...

 void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
    {
        if (e.Mode == PowerModes.Suspend) PauseTimer();
        else if (e.Mode == PowerModes.Resume) ResumeTimer();
    }
Cerebration answered 1/1, 2011 at 17:24 Comment(3)
what is purpose for SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;Surovy
This is event/delegate assignment. Whenever the event SystemEvents.PowerModeChanged is fired, the method SystemEvents_PowerModeChanged will get called, with the mode in the parameter e, which is passed into the function. Have not verified this, but seems like a plausible solution.Tetrapod
One important thing to note from the MSDN page for the SystemEvents.PowerModeChanged event is that you'll need to detach the event handler when your application is disposed: SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;.Focus

© 2022 - 2024 — McMap. All rights reserved.