Search code examples
c#pinvoke

Preventing computer from sleeping


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?


Solution

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