2

I have an application with some sort of media playing and I do not want the computer to sleep when my application runs. I searched around and came to know that this can be done by P/Invoke.

Neither should the display be turned off and neither should the computer go to sleep. So, I did the following to test this:

b.Click += (x, y) =>
                {
                    SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_AWAYMODE_REQUIRED);
                    Debug.WriteLine("Power line executed");
                };

 [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);

        [FlagsAttribute]
        public enum EXECUTION_STATE : uint
        {
            ES_AWAYMODE_REQUIRED = 0x00000040,
            ES_CONTINUOUS = 0x80000000,
            ES_DISPLAY_REQUIRED = 0x00000002,
            ES_SYSTEM_REQUIRED = 0x00000001
        }

However, the computer still went to sleep after some time. What's missing here?

torrential coding
  • 1,755
  • 2
  • 24
  • 34
Cipher
  • 5,894
  • 22
  • 76
  • 112

2 Answers2

4

Away mode is not supported on XP. Use Continuous | Display | System instead.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Well, doesn't matter, what your user runs is important. If you still have trouble then look in Control Panel + Power for something added by the vendor and messing this up. – Hans Passant Apr 07 '12 at 07:00
  • I though this page http://pinvoke.net/default.aspx/kernel32/SetThreadExecutionState.html only referred to Monitor Power down with with `Continuous` and `Display Required` flags. Is that correct or `Continous` and `Display Required` would also prevent from sleep? For me: this doesn't work and the computer still sleeps and I'm on standard home OS with default power settings. – Cipher Apr 07 '12 at 07:03
3

SetThreadExecutionState

To enable away mode, an application uses both ES_AWAYMODE_REQUIRED and ES_CONTINUOUS; to disable away mode, an application calls SetThreadExecutionState with ES_CONTINUOUS and clears ES_AWAYMODE_REQUIRED. When away mode is enabled, any operation that would put the computer to sleep puts it in away mode instead. The computer appears to be sleeping while the system continues to perform tasks that do not require user input. Away mode does not affect the sleep idle timer; to prevent the system from entering sleep when the timer expires, an application must also set the ES_SYSTEM_REQUIRED value.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150