大家好,我的应用程序需要将PC置于睡眠模式并在特定时间后唤醒它。 为了研究这种情况,我制作了一个简单的控制台应用程序,将PC休眠并在10秒后唤醒。特定时间后从睡眠中唤醒c#
对谷歌经过长期的研究,并在这里对堆栈后,我发现,通常所有的答案去这个示例: http://www.anotherchris.net/csharp/wake-up-from-sleep-createwaitabletimer-in-csharp/
1)我试图在一台PC(Windows 7)中,它睡觉去了,但没不醒来 2)现在试图使它在另一台PC(Windows 10)上工作,但它甚至不会达到该功能的结束......-可能会一直等待在:wh.waitOne line ...
所以这里是我的代码 - 我做错了什么?!? - 将欣赏任何帮助....或以另一种方式提出建议...
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();
}
}
}
检查唤醒定时器在'控制Panel'当前的电源计划设置中启用。 – Loathing