Hi everybody my application needs to put PC to the Sleep mode and Wake it Up after certain period. To investigate this case i made simple Console application to put PC Sleep and wake it up after 10 seconds .
after a long research on google and here on Stack i found that generally all answers goes to this sample: http://www.anotherchris.net/csharp/wake-up-from-sleep-createwaitabletimer-in-csharp/
1)I tried it on one pc (windows 7) and it went to sleep but did not wake up 2) now trying to make it work on another PC (windows 10) but it even does not get to the end of the function...- probably stays waiting at : wh.waitOne line ...
so here is my code- what am i doing wrong?!?- will appreciate any help.... or suggestions on another way doing it ...
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Threading;
using System.ComponentModel;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
[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);
static void Main(string[] args)
{
SetWaitForWakeUpTime();
Application.SetSuspendState(PowerState.Suspend, false, false);
}
static void SetWaitForWakeUpTime()
{
DateTime utc = DateTime.Now.AddSeconds(5);
long duetime = utc.ToFileTime();
using (SafeWaitHandle handle = CreateWaitableTimer(IntPtr.Zero, true, "MyWaitabletimer"))
{
if (SetWaitableTimer(handle, ref duetime, 0, IntPtr.Zero, IntPtr.Zero, true))
{
using (EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.AutoReset))
{
wh.SafeWaitHandle = handle;
wh.WaitOne();
}
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
// You could make it a recursive call here, setting it to 1 hours time or similar
Console.WriteLine("Wake up call");
Console.ReadLine();
}
}
}