2015-11-03 87 views
0

大家好,我的应用程序需要将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(); 
     } 
    } 
} 
+1

检查唤醒定时器在'控制Panel'当前的电源计划设置中启用。 – Loathing

回答

0

在CodeProject上一个项目上,让这样的一个例子: http://www.codeproject.com/Articles/49798/Wake-the-PC-from-standby-or-hibernation

不过,我在评论在其他地方看到,并不是所有的主板都支持该应用程序中使用的功能,所以它可能在一些但不是所有的计算机上工作。

+0

我已经看到它 - 它使完全相同的代码...刚从不同的线程开始....有一个程序:http://www.passmark.com/products/sleeper.htm,完美的作品我的个人电脑 - 并使这正是......-我试图做同样的...... –

+0

我很好奇,如果他们的程序是以编程方式使用任务计划程序来安排一个任务,唤醒电脑。 http://stackoverflow.com/a/3764944 –

1

我使用了Task Scheduler Managed Wrapper。这是我的问题的一个很好的解决方案:

做一个计划的任务发射一段时间后,它从睡眠唤醒PC。我制作了一个带有“退出”的小型“cmd.exe”执行脚本,用于安排任何事情。

我用:https://taskscheduler.codeplex.com/

+0

你可能想使用[rundll32.exe没有参数](http://superuser.com/questions/381103/is-there-a-windows-exe-that而不是)。 –