Windows 在 运行 长 C++ Visual Studio 程序时休眠

Windows sleeps while running a long C++ Visual Studio program

我正在使用 Windows 8.1,Visual Studio 2013,我有一个运行超过 15 分钟的 C++ 项目。但问题是 windows 在我仍在调试时进入睡眠状态。

我知道这是因为 运行 程序(调试)时超过了睡眠等待时间,我可以通过增加睡眠等待时间或将设置设置为 "never" 在 Windows 控制面板电源设置中休眠。

但我想要一个基于程序或 Visual Studio 的解决方案。我希望我的计算机在程序执行(调试)过程中不休眠。

windows中有SetThreadExecutionState函数

在程序入口点更改设置,在调试会话结束时在最后恢复设置。

举个例子....

#include <cstdlib>
//include windows.h

using namespace std;

void KeepMonitorActive() {
    // Enable away mode and prevent the sleep idle time-out.
    SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED);
}

void RestoreMonitorSettings() {
    // Clear EXECUTION_STATE flags to disable away mode and allow the system to idle to sleep normally.
    SetThreadExecutionState(ES_CONTINUOUS);
}

int main()
{
    //Add these 2 lines at the entry point in your program
    KeepMonitorActive();
    atexit(RestoreMonitorSettings);

   //...
}