Sleep apnea is not normally a good thing, but I needed to prevent our workstations from going to sleep. Our domain workstations were going to sleep in the middle
of third party model runs, and a group policy overrode any local power settings.
What problem does this solution solve?
This Visual Basic (2010) utility uses the
SetThreadExecutionState API to inform the system that it is in use, thereby preventing the system from entering sleep
or turning off the display while the application is running. The system automatically detects activities such as local keyboard or mouse input, server activity,
and changing window focus (which all will keep a system from going to sleep). But disk, CPU activity, and video display are activities that are not automatically
detected (and a long running process is not enough to keep a system awake).
How does the code work?
The application calls the
SetThreadExecutionState API once when the form is loaded. The system will not sleep (or turn off the display) as long as this application is running.
Private Declare Function uses the SetThreadExecutionState Lib _
"kernel32" (ByVal esflags As EXECUTION_STATE) As EXECUTION_STATE
Private Enum EXECUTION_STATE
ES_SYSTEM_REQUIRED = &H1
ES_DISPLAY_REQUIRED = &H2
ES_CONTINUOUS = &H80000000
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Private Function No_Sleep() As EXECUTION_STATE
Return SetThreadExecutionState(EXECUTION_STATE.ES_SYSTEM_REQUIRED Or _
EXECUTION_STATE.ES_CONTINUOUS Or EXECUTION_STATE.ES_DISPLAY_REQUIRED)
API execution states (
ES_CONTINUOUS) are explained
A button on the form flashes red every five seconds (users like to know something is happening).
Private Sub NoSleep_Timer_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles NoSleep_Timer.Tick
Dim Save_Backcolor As Color = Status_Button.BackColor
Status_Button.BackColor = Color.Red
Status_Button.BackColor = Save_Backcolor
Users can double click on the application to minimize the application to the system tray. A balloon tip is displayed when it's minimized so users know which icon is used.
Private Sub Form1_DoubleClick(sender As Object, _
e As System.EventArgs) Handles Me.DoubleClick
Private Sub MinimizeAppToTray()
NoSleep_NotifyIcon.Visible = True
Users can double click on the system tray icon to show the application window again, or right click on the icon to close the application (see full source code for these functions).
Points of interest
This was tested and works on Windows XP (both 32/64 bit), Vista, and Windows 7 systems.
Here are the check sums of the no_sleep.exe compiled application (verify file integrity prior to executing, or recompile to be on the safe side).
- Version 1 posted 25 Nov 2011.
- Version 2 posted 27 Nov 2011 (changed source code zip file name - with same code).