c#实现系统休眠
作者:互联网
c#实现系统休眠
class SystemSleepManagement
{
//定义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)
{
if (includeDisplay)
SetThreadExecutionState(ExecutionFlag.System | ExecutionFlag.Display | ExecutionFlag.Continus);
else
SetThreadExecutionState(ExecutionFlag.System | ExecutionFlag.Continus);
}
/// <summary>
///恢复系统休眠
/// </summary>
public static void ResotreSleep()
{
SetThreadExecutionState(ExecutionFlag.Continus);
}
/// <summary>
///重置系统休眠计时器
/// </summary>
/// <param name="includeDisplay">是否阻止关闭显示器</param>
public static void ResetSleepTimer(bool includeDisplay = false)
{
if (includeDisplay)
SetThreadExecutionState(ExecutionFlag.System | ExecutionFlag.Display);
else
SetThreadExecutionState(ExecutionFlag.System);
}
}
因此,要实现下载时阻止程序休眠,则有两种实现方式:
下载期间起计时器定期执行ResetSleepTimer函数
下载开始时执行PreventSleep函数,下载结束后执行ResotreSleep函数。
另外,和阻止系统休眠类似,有的程序还需要有阻止屏保功能。
标签:Continus,c#,系统,System,休眠,static,ExecutionFlag,SetThreadExecutionState 来源: https://www.cnblogs.com/ouyangkai/p/16660364.html