2

Is there a way to stop system from going to sleep/hibernate mode when user presses e.g. laptop's or tablet's power button or chooses sleep/hibernate from Windows' menu? I've been trying to implement this by using WndProc and Windows' power messages but no luck. Here's the code that I've been using. I also tried to return BROADCAST_QUERY_DENY as IntPtr but no luck.

protected override void OnSourceInitialized(EventArgs e)
{
    base.OnSourceInitialized(e);
    HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
    source.AddHook(WndProc);
}

private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    if (msg == 0x218) // WM_POWERBROADCAST.
    {
        if (wParam.ToInt32() == 0x4) // PBT_APMSUSPEND.
        {
            handled = true;
        }
    }
    return IntPtr.Zero;
}

I've also tried PowerCreateRequest and PowerSetRequest but no luck there either.

I have managed to prevent Windows from shutting down by using Microsoft.Win32.SystemEvents.SessionEnding and I thought that this handles power management messages too but I was wrong. :)

Chris Schiffhauer
  • 17,102
  • 15
  • 79
  • 88
  • possible duplicate http://stackoverflow.com/questions/629240/prevent-windows-from-going-into-sleep-when-my-program-is-running – Boklucius Feb 24 '14 at 15:03
  • I'd say it's closer to http://stackoverflow.com/questions/7457000/net-setting-power-options-from-code – Tewr Feb 24 '14 at 15:42
  • Hi. Like I said, I tried the power availability requests but no luck. I even copy-pasted the same code from the document (http://msdn.microsoft.com/en-us/library/windows/hardware/gg463205.aspx) to be sure but nothing. When I click "Sleep" from Windows 8's Settings menu ("Power") my computer goes to sleep instantly.Actually when I used SetThreadExecutionState it kinda worked. My monitor went black but my computer didn't power off. However, they say that power availability requests is the way to go with Windows 7 or higher. Go figure... –  Feb 25 '14 at 16:24
  • I'd like to use these requests rather than WndProc or SetThreadExecutionState. The document says how easy these requests are to use but they don't work in my case... I will play with this some more but if someone has any idea what might be wrong, don't hesitate to post a comment. :) –  Feb 25 '14 at 16:36

0 Answers0