Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using Windows 8.1, Visual Studio 2013 and I have a C++ project which runs over 15 minutes. But the problem is the windows gets into sleep while my is still debugging.

I know this is occured because the sleep wait time is exceeded while running the program (debugging), and I can easily stop this by either increasing sleep wait time or set the settings to "never" sleep in the Windows Control Pannel Power Settings.

But I want a programatical or Visual Studio based solution for this. I want my computer not to sleep in the midst of execution (debugging) of a program.

like image 418
Samitha Chathuranga Avatar asked Sep 15 '15 04:09

Samitha Chathuranga


2 Answers

There is SetThreadExecutionState function in windows

like image 58
Dmitrii Z. Avatar answered Nov 10 '22 07:11

Dmitrii Z.


At the program entry point change the settings, restore settings at the end when debug session finishes.

Take this example....

#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);

   //...
}
like image 44
user1 Avatar answered Nov 10 '22 08:11

user1