I'm trying to make my pc wake up in case it has gotten into sleep mode. I found this code snippet on some website, but the Messagebox I added at the end always returns immediately.
I have also enabled my system for the use of wake timers in the power options.
[DllImport("kernel32.dll")]
public static extern IntPtr CreateWaitableTimer(IntPtr lpTimerAttributes,
bool bManualReset, string lpTimerName);
[DllImport("kernel32.dll")]
public static extern bool SetWaitableTimer(IntPtr hTimer, [In] ref long
pDueTime, int lPeriod, IntPtr pfnCompletionRoutine, IntPtr
lpArgToCompletionRoutine, bool fResume);
[DllImport("kernel32", SetLastError = true, ExactSpelling = true)]
public static extern Int32 WaitForSingleObject(IntPtr handle, uint
milliseconds);
static IntPtr handle;
private void SetWaitForWakeUpTime()
{
long duetime = 1200000000;
handle = CreateWaitableTimer(IntPtr.Zero, true, "MyWaitabletimer");
SetWaitableTimer(handle, ref duetime, 0, IntPtr.Zero, IntPtr.Zero, true);
uint INFINITE = 0xFFFFFFFF;
int ret = WaitForSingleObject(handle, INFINITE);
MessageBox.Show("wake up !");
}
and I'm calling it like this:
private void buttonTest_Click(object sender, EventArgs e)
{
SetWaitForWakeUpTime();
}
Theoretically this should only be signalled after 2 minutes, right? Why is it signalled right away and how do I correct it?
SetWaitableTimer() can trigger both on an absolute and incremental time. From the MSDN article:
pDueTime [in]
The time after which the state of the timer is to be set to signaled, in 100 nanosecond intervals. Use the format described by the FILETIME structure. Positive values indicate absolute time. Be sure to use a UTC-based absolute time, as the system uses UTC-based time internally. Negative values indicate relative time. The actual timer accuracy depends on the capability of your hardware. For more information about UTC-based time, see System Time.
Right now you used a positive value so you specified a date in the year 1600, it always instantly completes. Looks like your actual intention was to use a 2 minute interval so you must use a negative value, -1200000000.
Probable true intention is to make it wake up at a specific time on the clock, given the usage scenario, use DateTime.ToUniversalTime().ToFileTime()