待機可能なタイマーを使用して、サスペンドまたは休止状態から復帰できます。私が見つけた限りでは、通常のシャットダウン モード (ソフト オフ/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();
}