How to make the machine go to sleep for some time and then wake up automatically?

Answered How to make the machine go to sleep for some time and then wake up automatically?

  • Friday, April 27, 2012 12:26 AM
     
     

    Dear all,

    I need to write a function like this:

    void GotoSleepAndThenWakeup(DateTime StartSleepTime, TimeSpan SleepTimeLength)

    {

      when the time reaches StartSleepTime, make the computer go to sleep, in order to save electical power.

      after sleep for SleepTimeLength, the computer can wake up automatically, because there is no person to manually wake up the computer.

    }

    Is it possible to implement this function? If yes, could you give me some suggestion?

    thanks,

    Jinmin


    [my homepage] http://directfriends.net/

    • Moved by Annabella Luo Tuesday, May 01, 2012 5:18 AM (From:Windows Presentation Foundation (WPF))
    •  

All Replies

  • Tuesday, May 01, 2012 5:16 AM
     
     

    Hi Jinmin,

    According to your description, I understand your issue is about windows desktop development issue, so I'm moving your thread to Developing Windows Desktop Applications with Power Management forum, so that you can get a better help.

    Thank you for your understanding and support.

    Have a nice day.


    Annabella Luo[MSFT]
    MSDN Community Support | Feedback to us

  • Wednesday, May 02, 2012 9:32 AM
     
     Answered
    • In "Control Panel > Power Options > Change Plan Settings > Change Advanced Power Settings > Sleep > Allow Wake Timers", all items are enabled.
    • If there is no password set on your Windows account, make sure that in "Control Panel > Power Options > Change Plan Settings > Change Advanced Power Settings > Brad / Additional Settings > Require a password on wakeup", all items are disabled (thanks nanfang).

    using System;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.ComponentModel;
    using System.Threading;
    using System.Windows.Forms;
    using Microsoft.Win32.SafeHandles;

    namespace Dugeit
    {
      public class Sleeper
      {
        [Flags()]
        public enum EXECUTION_STATE : uint
        {
          ES_CONTINUOUS = 0X80000000,
          ES_DISPLAY_REQUIRED = 0X2,
          ES_SYSTEM_REQUIRED = 0X1,
          ES_AWAYMODE_REQUIRED = 0X40
        }
        private const int VK_NONAME = 0XFC;
        private const byte KEYEVENTF_SILENT = 0X4;

        [DllImport("kernel32.dll")]
        public static extern SafeWaitHandle CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName);

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetWaitableTimer(SafeWaitHandle hTimer, [In] ref long pDueTime, int lPeriod, IntPtr pfnCompletionRoutine, IntPtr lpArgToCompletionRoutine, bool fResume);

        [DllImport("Kernel32.DLL", CharSet = CharSet.Auto, SetLastError = true)]
        protected extern static EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE state);

        [DllImport("user32.dll")]
        private extern static void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);

        public event EventHandler Woken;
        private BackgroundWorker bgWorker = new BackgroundWorker();
        System.Timers.Timer SleepTimer = new System.Timers.Timer(5000) { AutoReset=false};

        public Sleeper()
        {
          bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
          bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
          SleepTimer.Elapsed += new System.Timers.ElapsedEventHandler(SleepTimer_Elapsed);
        }

        public void SetWakeUpTime(DateTime time)
        {
          bgWorker.RunWorkerAsync(time.ToFileTime());
        }

        private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
          long waketime = (long)(e.Argument);
          using (SafeWaitHandle timer = CreateWaitableTimer(IntPtr.Zero, true, this.GetType().Assembly.GetName().Name.ToString() + "Timer"))
          {
            if (SetWaitableTimer(timer, ref waketime, 0, IntPtr.Zero, IntPtr.Zero, true))
            {
              using (EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.AutoReset))
              {
                wh.SafeWaitHandle = timer;
                SleepTimer.Start();
                wh.WaitOne();
              }
            }
            else
            {
              throw new Win32Exception(Marshal.GetLastWin32Error());
            }
          }
          SetThreadExecutionState(EXECUTION_STATE.ES_SYSTEM_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
          SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED);
          keybd_event(VK_NONAME, 0, KEYEVENTF_SILENT, 0);
        }

        void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
          if (Woken != null)
          {
            Woken(this, new EventArgs());
          }
        }

        void SleepTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
          Application.SetSuspendState(PowerState.Hibernate, true, false);
        }

      }
    }


    [my homepage] http://directfriends.net/


    • Edited by 淨明 Wednesday, May 02, 2012 9:34 AM
    • Marked As Answer by 淨明 Wednesday, May 02, 2012 9:34 AM
    •