using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace DayOf1440.Utils
{
public static class SystemSleep
{
[DllImport("kernel32")]
private static extern ExecutionState SetThreadExecutionState(ExecutionState esFlags);
[Flags]
private enum ExecutionState : uint
{
///
/// Forces the system to be in the working state by resetting the system idle timer.
///
SystemRequired = 0x01,
///
/// Forces the display to be on by resetting the display idle timer.
///
DisplayRequired = 0x02,
///
/// This value is not supported. If is combined with other esFlags values, the call will fail and none of the specified states will be set.
///
[Obsolete("This value is not supported.")]
UserPresent = 0x04,
///
/// Enables away mode. This value must be specified with .
///
/// Away mode should be used only by media-recording and media-distribution applications that must perform critical background processing on desktop computers while the computer appears to be sleeping.
///
AwaymodeRequired = 0x40,
///
/// Informs the system that the state being set should remain in effect until the next call that uses and one of the other state flags is cleared.
///
Continuous = 0x80000000,
}
///
/// 设置此线程此时开始一直将处于运行状态,此时计算机不应该进入睡眠状态。
/// 此线程退出后,设置将失效。
/// 如果需要恢复,请调用 方法。
///
///
/// 表示是否应该同时保持屏幕不关闭。
/// 对于游戏、视频和演示相关的任务需要保持屏幕不关闭;而对于后台服务、下载和监控等任务则不需要。
///
public static void PreventForCurrentThread(bool keepDisplayOn = true)
{
SetThreadExecutionState(keepDisplayOn
? ExecutionState.Continuous | ExecutionState.SystemRequired | ExecutionState.DisplayRequired
: ExecutionState.Continuous | ExecutionState.SystemRequired);
}
///
/// 恢复此线程的运行状态,操作系统现在可以正常进入睡眠状态和关闭屏幕。
///
public static void RestoreForCurrentThread()
{
SetThreadExecutionState(ExecutionState.Continuous);
}
///
/// 重置系统睡眠或者关闭屏幕的计时器,这样系统睡眠或者屏幕能够继续持续工作设定的超时时间。
///
///
/// 表示是否应该同时保持屏幕不关闭。
/// 对于游戏、视频和演示相关的任务需要保持屏幕不关闭;而对于后台服务、下载和监控等任务则不需要。
///
public static void ResetIdle(bool keepDisplayOn = true)
{
SetThreadExecutionState(keepDisplayOn
? ExecutionState.SystemRequired | ExecutionState.DisplayRequired
: ExecutionState.SystemRequired);
}
}
}