- 1 year ago
Prevent screen from sleeping with C#
To prevent the screen from sleeping or the computer from going into sleep mode using C#, you can utilize the SetThreadExecutionState
function from the kernel32.dll
library. This function allows you to control the system's idle behavior. Here's how you can use it:
csharpusing System;
using System.Runtime.InteropServices;
class Program
{
// Import the SetThreadExecutionState function
[DllImport("kernel32.dll")]
static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
// Enumeration for execution state flags
[Flags]
public enum EXECUTION_STATE : uint
{
ES_CONTINUOUS = 0x80000000,
ES_SYSTEM_REQUIRED = 0x00000001,
ES_DISPLAY_REQUIRED = 0x00000002
}
static void Main(string[] args)
{
// Prevent the screen from sleeping
SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_DISPLAY_REQUIRED);
// Your code here
// Restore default execution state
SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
}
}
In this example, the SetThreadExecutionState
function is used to prevent the screen from sleeping by specifying the ES_DISPLAY_REQUIRED
flag. This code will prevent the system from going into sleep mode as long as the execution state remains set.
Remember to restore the default execution state by calling SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS)
after your code execution is complete.
Please note that using this method requires appropriate privileges, and in some cases, system policies may override your request to prevent sleep. Additionally, it's important to balance preventing sleep with user experience and energy conservation considerations.