大家好,我的应用程序需要将PC置于睡眠模式,并在一定时间后唤醒它。为了调查这个案例,我制作了一个简单的控制台应用程序,让电脑进入睡眠状态,并在10秒钟后将其唤醒。
经过对谷歌和Stack的长期研究,我发现通常所有的答案都指向这个样本:http://www.anotherchris.net/csharp/wake-up-from-sleep-createwaitabletimer-in-csharp/
1) 我在一台电脑(windows 7)上试了一下,它睡着了,但没有醒来2) 现在正试图让它在另一台电脑上工作(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();
}
}
}
我使用了任务调度器托管包装器。这是一个很好的解决我的问题:
让一个预定任务在一段时间后启动,它会将电脑从睡眠中唤醒。我做了一个小的"cmd.exe"执行脚本,里面有"exit",什么都不安排。
我曾经:https://taskscheduler.codeplex.com/
CodeProject上有一个项目给出了这样做的例子:http://www.codeproject.com/Articles/49798/Wake-the-PC-from-standby-or-hibernation
然而,我在其他地方的评论中看到,并不是所有的主板都支持该应用程序中使用的功能,所以它可能适用于某些计算机,但不是所有计算机。
Duetime应该是负数,并以数百纳秒表示。以下示例将在30秒内唤醒计算机。
long duetime = -300000000;
msdnhttps://msdn.microsoft.com/en-us/library/windows/desktop/ms686289(v=vs.85).aspx