我正在努力阻止 Windows 11 休眠。
我尝试了以下的每一种组合:
ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED
for (;;)
{
SetThreadExecutionState(ES_SYSTEM_REQUIRED);
// SetThreadExecutionState(ES_SYSTEM_REQUIRED | ES_CONTINUOUS);
// SetThreadExecutionState(ES_AWAYMODE_REQUIRED)
// SetThreadExecutionState(ES_AWAYMODE_REQUIRED | ES_CONTINUOUS);
// SetThreadExecutionState(ES_AWAYMODE_REQUIRED | ES_SYSTEM_REQUIRED | ES_CONTINUOUS);
Thread.Sleep(10000);
Console.WriteLine("The current time is: " + DateTime.Now);
}
private const uint ES_CONTINUOUS = 0x80000000;
private const uint ES_SYSTEM_REQUIRED = 0x00000001;
private const uint ES_DISPLAY_REQUIRED = 0x00000002;
private const uint ES_AWAYMODE_REQUIRED = 0x00000040;
我已经在for循环内部和for循环外部尝试过。
我所做的任何事情都无法阻止系统在大约 3 - 5 分钟后进入睡眠状态。
在 Windows 11 中是否有不同的方法来执行此操作?
using System;
using System.Runtime.InteropServices;
public class PreventSleep
{
// ES_AWAYMODE_REQUIRED is a flag that specifies to the system that Away Mode should be enabled,
// keeping the system running even when it would otherwise enter a low-power state.
private const uint ES_AWAYMODE_REQUIRED = 0x00000040;
// The ES_CONTINUOUS flag indicates that the operating system should consider the thread's activity
// as user-initiated, meaning it should not enter sleep mode while the thread is active.
private const uint ES_CONTINUOUS = 0x80000000;
// ES_DISPLAY_REQUIRED is a flag that specifies to the system that the display should
// remain on and not enter sleep mode due to inactivity.
private const uint ES_DISPLAY_REQUIRED = 0x00000002;
// The ES_SYSTEM_REQUIRED flag specifies that the system should not enter sleep mode.
private const uint ES_SYSTEM_REQUIRED = 0x00000001;
// ES_USER_PRESENT is a flag that specifies to the system that a user is present and interacting
// with the system, preventing the system from entering sleep or idle states.
private const uint ES_USER_PRESENT = 0x00000004;
// The SetThreadExecutionState function is imported using DllImport from kernel32.dll.
// This allows your C# code to call this native Windows API function.
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern uint SetThreadExecutionState(uint esFlags);
public static void PreventSleepMode()
{
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
}
public static void AllowSleepMode()
{
SetThreadExecutionState(ES_CONTINUOUS);
}
}
How to use it?
// Prevent Sleep
PreventSleep.PreventSleepMode();
// Allow Sleep
PreventSleep.AllowSleepMode();