SamFisher83
SamFisher83

Reputation: 3995

How to detect if windows is going to hibernate or suspend?

I am using

SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(
    SystemEvents_PowerModeChanged
);

to tell when Windows is suspending. But how do I know if it is going into hibernate or suspend?

Is there a .Net or PInvoke method to do this?

Upvotes: 17

Views: 11651

Answers (3)

Joe-700
Joe-700

Reputation: 1

I use the 'Suspend' status of the e.mode argument to trigger actions when the system goes into shutdown.

//Register for event
SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;

//Do stuff when system shutsdown
private static void SystemEvents_PowerModeChanged(object sender, 
PowerModeChangedEventArgs e)
{
if (e.Mode.ToString() == "Suspend")
{
//do stuff
}

You can also use the following event to trigger in the event of Hybernation:

//Register for session ending events
SystemEvents.SessionEnding += c_SessionEndedEvent;

//The delegate handler
private static void c_SessionEndedEvent(object sender, SessionEndingEventArgs e)
{
//Do stuff here
}

You can also use the PowerModeChanged event to specify behaviour when the system wakes back up.

This will not work when the system goes to sleep though... however I have never come across a situation where I have wanted to do this.

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283614

You can't tell the difference between hibernate and suspend.

A detailed discussion here.

The takeaway message is that your question presupposes a false dichotomy: It can be hibernate, suspend, or hybrid sleep... and when hybrid sleep transitions from suspend to hibernate user code isn't even running (in fact there may be no code running, the transition happens in case of power loss).

So when the decision to hybrid sleep occurs, the system doesn't know whether it will resume from suspend or from hibernation, and it can't tell you what it doesn't know.

Upvotes: 11

Jamie Howarth
Jamie Howarth

Reputation: 3323

According to MSDN, the value of e.Mode (your event handler should have a second parameter of PowerChangedEventArgs e) will be an enum of one of "Resume", "StatusChange" or "Suspend". However, it doesn't appear to provide more detail than this, so one assumes that if the status is Suspend, then the PC is either sleeping or hibernating.

HTH,

Benjamin

Upvotes: 2

Related Questions