Friday, February 14, 2014

Prevent Standby Mode

If one listens for example to music or watches a movie, the Windows computer does not enter the power saving mode / sleep mode despite the missing user interaction. But with a running C# application it does.
Today I want to show how to prevent this. For that we have to include the function SetThreadExecutionState() via P/Invoke, with which we can tell the system, that the program needs it right now.
Induced states can be amongst others:

  • ES_DISPLAY_REQUIRED: This mode prevents the shutting off of the displays.
  • ES_SYSTEM_REQUIRED: This mode prevents the shutting off of the whole system. 
If you call the function with one of these states alone, just the timer for the respective event is reset, meaning from the time of execution on the system counts as idle again and after the elapse of the set time the display / system is turned off.
To avoid the shutdown completely, the function either has to be called periodically or you combine the state with ES_CONTINOUS, then a single call is sufficient.
The following example program on startup tells the operating system, that it never is supposed to go to sleep:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public enum EXECUTION_STATE : uint
        {
            ES_AWAYMODE_REQUIRED = 0x00000040,
            ES_CONTINUOUS = 0x80000000,
            ES_DISPLAY_REQUIRED = 0x00000002,
            ES_SYSTEM_REQUIRED = 0x00000001
        }

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

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_SYSTEM_REQUIRED);
        }
    }
}

1 comment: