Click here to Skip to main content
Click here to Skip to main content

Keep Alive the Machine - No Sleep

, 7 Dec 2011
Rate this:
Please Sign up or sign in to vote.
This app will keep the machine running


This is a very simple application that keeps the computer from sleeping. Nothing very fancy, but it seems useful when you cannot control the power options (managed by your domain admin) but you want your PC to stay awake occasionally.

Using the Code

    internal static class NativeMethods
        // Import SetThreadExecutionState Win32 API and necessary flags
        public static extern uint SetThreadExecutionState(uint esFlags);
        public const uint ES_CONTINUOUS = 0x80000000;
        public const uint ES_SYSTEM_REQUIRED = 0x00000001;

public partial class MainForm : Form
        private uint m_previousExecutionState;

        public MainForm()

        private void MainForm_Load(object sender, EventArgs e)
            // Set new state to prevent system sleep (note: still allows screen saver)
            m_previousExecutionState = NativeMethods.SetThreadExecutionState(
                NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED);
            if (0 == m_previousExecutionState)
                MessageBox.Show("Failed to set system state.",  
        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // No way to recover; fail gracefully

        protected override void OnClosed(System.EventArgs e)

            // Restore previous state
            if (0 == NativeMethods.SetThreadExecutionState(m_previousExecutionState))
                // No way to recover; already exiting



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Maruf Maniruzzaman
Software Developer KAZ Software Ltd. Bangladesh.
Bangladesh Bangladesh
Have completed BSc in Computer Science & Engineering from Shah Jalal University of Science & Technology, Sylhet, Bangladesh (SUST).
Story books (specially Masud Rana series), tourism, songs and programming is most favorite.
Maruf Notes
Working on small project for 2 factor authentication

Comments and Discussions

QuestionProbably better as a tip/trick PinprofessionalCraigDJ24-Jan-14 12:21 
GeneralMy vote of 4 PinmemberKim Togo6-Dec-11 0:34 
The same rules applies to programs running as Windows Service.
GeneralMy vote of 4 PinmemberAddy Tas3-Dec-11 3:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 7 Dec 2011
Article Copyright 2011 by Maruf Maniruzzaman
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid