One of my colleague ask me about how to “prevent standby” from csharp code.
It obviously has nothing to do with csharp or any kind of .net languages.
The real solution rely on Kernel32.dll SetThreadExecutionState API.
Lets check out the msdn and write the code with Csharp.

Msdn says for SetThreadExecutionState:
Enables an application to inform the system that it is in use, thereby preventing the system from entering sleep or turning off the display while the application is running.
Return Value
If the function succeeds, the return value is the previous thread execution state.
If the function fails, the return value is NULL.

Cool. Ok lets see what pinvoke.net says about this.
SetThreadExecutionState is used to stop the machine timing out and entering standby/switching the display device off.

Ok. Thats exactly what we want!

Prepare the enum, then [DllImport] attribute and then Prevent and Allow Methods.

    public static class NativeCalls
    {
        [FlagsAttribute]
        public enum EXECUTION_STATE : uint
        {
            ES_SYSTEM_REQUIRED = 0x00000001,
            ES_DISPLAY_REQUIRED = 0x00000002,
            ES_CONTINUOUS = 0x80000000,
        }

        //Do not forget to add the System.Runtime.InteropServices using directive
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);

        public static void PreventMonitorPowerdown()
        {
            SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED |
                                EXECUTION_STATE.ES_CONTINUOUS);
        }

        public static void AllowMonitorPowerdown()
        {
            SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
        }
    }

And read carefully the pinvoke’s note:
There is no need to store the state you set, Windows remembers it for you. Just set it back to ES_CONTINUOUS when you don’t want it anymore. Also note that this setting is per thread/application not global, so if you go to ES_CONTINUOUS and another app/thread is still setting ES_DISPLAY the display will be kept on. Note that the return value is the EXECUTION_STATE that ”was” set.

After all don’t forget the compile with -unsafe option.

Did you like this? Share it: