Created
February 19, 2013 14:31
-
-
Save yetanotherchris/4986402 to your computer and use it in GitHub Desktop.
Wake up from sleep C# example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
using Microsoft.Win32.SafeHandles; | |
using System.Threading; | |
using System.ComponentModel; | |
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(); | |
} | |
static void SetWaitForWakeUpTime() | |
{ | |
DateTime utc = DateTime.Now.AddMinutes(2); | |
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment