一、测试
测试环境:Win10
备注:
1、管理员和非管理员权限测试都正常;
2、执行阻止关闭显示器和待机后,退出程序会自动恢复;
3、使用Win+L切换到锁屏界面时,同样生效;
二、代码
代码来源:
https://www.cnblogs.com/TianFang/archive/2012/10/12/2721883.html
public class SystemSleepAPI
{
[DllImport("kernel32.dll")]
static extern uint SetThreadExecutionState(ExecutionFlag flags);
[Flags]
enum ExecutionFlag : uint
{
System = 0x00000001,
Display = 0x00000002,
Continus = 0x80000000,
}
public static void PreventSleep(bool includeDisplay = false)
{
try
{
if (includeDisplay)
SetThreadExecutionState(ExecutionFlag.System | ExecutionFlag.Display | ExecutionFlag.Continus);
else
SetThreadExecutionState(ExecutionFlag.System | ExecutionFlag.Continus);
}
catch { }
}
public static void ResotreSleep()
{
try { SetThreadExecutionState(ExecutionFlag.Continus); } catch { }
}
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函数