如何以编程方式在特定时间唤醒Windows XP(或更高版本)计算机最佳方法?(最好像Media Center那样自动启动以录制特定的电视节目)
我有一个Windows服务(用C#编写),我希望该服务能够在预定的时间唤醒托管它的计算机。
是否需要配置任何BIOS设置或先决条件(例如ACPI)才能使其正常工作?
由于此计算机将使用拨号或3G无线调制解调器,因此不幸的是,它不能依赖Wake on LAN。
如何以编程方式在特定时间唤醒Windows XP(或更高版本)计算机最佳方法?(最好像Media Center那样自动启动以录制特定的电视节目)
我有一个Windows服务(用C#编写),我希望该服务能够在预定的时间唤醒托管它的计算机。
是否需要配置任何BIOS设置或先决条件(例如ACPI)才能使其正常工作?
由于此计算机将使用拨号或3G无线调制解调器,因此不幸的是,它不能依赖Wake on LAN。
你可以使用可等待计时器来从挂起或休眠状态唤醒。据我所知,无法以编程方式从正常关闭模式(软关机/S5)中唤醒,在这种情况下,您需要在BIOS中指定WakeOnRTC闹钟。要从C#中使用可等待计时器,您需要使用pInvoke。导入声明如下:
public delegate void TimerCompleteDelegate();
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetWaitableTimer(IntPtr hTimer, [In] ref long pDueTime, int lPeriod, TimerCompleteDelegate pfnCompletionRoutine, IntPtr pArgToCompletionRoutine, bool fResume);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CancelWaitableTimer(IntPtr hTimer);
您可以按照以下方式使用这些函数:
public static IntPtr SetWakeAt(DateTime dt)
{
TimerCompleteDelegate timerComplete = null;
// read the manual for SetWaitableTimer to understand how this number is interpreted.
long interval = dt.ToFileTimeUtc();
IntPtr handle = CreateWaitableTimer(IntPtr.Zero, true, "WaitableTimer");
SetWaitableTimer(handle, ref interval, 0, timerComplete, IntPtr.Zero, true);
return handle;
}
您可以使用返回的句柄作为参数,使用CancelWaitableTimer
取消可等待定时器。
您的程序可以使用pInvoke进行休眠和睡眠:
[DllImport("powrprof.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetSuspendState(bool hibernate, bool forceCritical, bool disableWakeEvent);
public static bool Hibernate()
{
return SetSuspendState(true, false, false);
}
public static bool Sleep()
{
return SetSuspendState(false, false, false);
}
您的系统可能不允许程序使计算机进入休眠状态。您可以调用以下方法来允许休眠:
public static bool EnableHibernate()
{
Process p = new Process();
p.StartInfo.FileName = "powercfg.exe";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.Arguments = "/hibernate on"; // this might be different in other locales
return p.Start();
}