I am creating a WPF app where I have to make device to sleep and awake at particular time. I tried to used SetWaitableTimer to do the same but due some mistakes my device is going into sleep but not able to do the awake part For testing purpose I have set the time of 1 minute to awake
Code
DateTime dateTime = DateTime.Now;
var dt = dateTime.AddMinutes(1);
Log.Info("WakeUp after " dt.ToString());
Utilities.TaskScheduler.SetWakeAt(dt);
Utilities.TaskScheduler.Sleep();
public delegate void TimerCompleteDelegate();
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetWaitableTimer(IntPtr hTimer, [In] ref long pDueTime, int lPeriod, TimerCompleteDelegate pfnCompletionRoutine, IntPtr pArgToCompletionRoutine, bool fResume);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CancelWaitableTimer(IntPtr hTimer);
[DllImport("powrprof.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetSuspendState(bool hibernate, bool forceCritical, bool disableWakeEvent);
public static bool Hibernate()
{
return SetSuspendState(true, false, false);
}
public static bool Sleep()
{
return SetSuspendState(false, false, false);
}
public static IntPtr SetWakeAt(DateTime dt)
{
TimerCompleteDelegate timerComplete = null;
// read the manual for SetWaitableTimer to understand how this number is interpreted.
long interval = dt.ToFileTimeUtc();
IntPtr handle = CreateWaitableTimer(IntPtr.Zero, true, "WaitableTimer");
SetWaitableTimer(handle, ref interval, 0, timerComplete, IntPtr.Zero, true);
return handle;
}
CodePudding user response:
I tried the same code and it worked for me. You have to understand when SetWaitableTimer will support for the system, if your bios support Awake sleep timer option then you are all good with this code.
option 1 : To check the awake sleep timer option , Go to control panel -> power option -> change current power plan -> click on advance setting and check the sleep dropdown
Option 2 : Open an elevated command prompt. Type the command below you want to use into the elevated command prompt, and press Enter.
(Add - default) REG ADD HKLM\SYSTEM\CurrentControlSet\Control\Power\PowerSettings\238C9FA8-0AAD-41ED-83F4-97BE242C8F20\BD3B718A-0680-4D9D-8AB2-E1D2B4AC806D /v Attributes /t REG_DWORD /d 2 /f
OR
(Remove) powercfg -attributes SUB_SLEEP BD3B718A-0680-4D9D-8AB2-E1D2B4AC806D ATTRIB_HIDE