一、测试

测试环境:Win10
备注:
1、管理员和非管理员权限测试都正常;
2、执行阻止关闭显示器和待机后,退出程序会自动恢复;
3、使用Win+L切换到锁屏界面时,同样生效;

二、代码


public class SystemSleepAPI
{
//定义API函数
[DllImport("kernel32.dll")]
static extern uint SetThreadExecutionState(ExecutionFlag flags);

[Flags]
enum ExecutionFlag : uint
{
System = 0x00000001,
Display = 0x00000002,
Continus = 0x80000000,
}

/// <summary>
///阻止系统休眠,直到线程结束恢复休眠策略
/// </summary>
/// <param name="includeDisplay">是否阻止关闭显示器</param>
public static void PreventSleep(bool includeDisplay = false)
{
try
{
if (includeDisplay)
SetThreadExecutionState(ExecutionFlag.System | ExecutionFlag.Display | ExecutionFlag.Continus);
else
SetThreadExecutionState(ExecutionFlag.System | ExecutionFlag.Continus);
}
catch { }
}

/// <summary>
///恢复系统休眠策略
/// </summary>
public static void ResotreSleep()
{
try { SetThreadExecutionState(ExecutionFlag.Continus); } catch { }
}

/// <summary>
///重置系统休眠计时器
/// </summary>
/// <param name="includeDisplay">是否阻止关闭显示器</param>
public static void ResetSleepTimer(bool includeDisplay = false)
{
try
{
if (includeDisplay)
SetThreadExecutionState(ExecutionFlag.System | ExecutionFlag.Display);
else
SetThreadExecutionState(ExecutionFlag.System);
}
catch { }
}
}

三、使用方法

方法1:计时器定期执行ResetSleepTimer函数
方法2:阻止时执行PreventSleep函数,恢复时执行ResotreSleep函数