C# 机器休眠设置

 

代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;

namespace testwakeup
{
class MyPowerMgr
{
private delegate void TimerSetDelegate(string WakeUpTime);
private delegate void TimerCompleteDelegate();



private static IntPtr handle;
private const uint INFINITE
= 0xFFFFFFFF;
private const long _SECOND
= 10000000;
private static long Interval
= 0;

public static void SetTimer(long sec)
{

Interval
= sec;
Thread t_Wait
= new Thread(new ThreadStart(WaitTimer));
t_Wait.Start();

}

private static void WaitTimer()
{


Int64 qwDueTime;
System.Runtime.InteropServices.ComTypes.FILETIME liDueTime;

qwDueTime
= -Interval * _SECOND;

// Copy the relative time into a FILETIME struct.

liDueTime.dwLowDateTime
= (Int32)(qwDueTime & 0xFFFFFFFF);
liDueTime.dwHighDateTime
= (Int32)(qwDueTime >> 32);

// Creating the timer delegate

TimerCompleteDelegate TimerComplete
= new TimerCompleteDelegate(TimerCompleted);

// Creating the timer
handle
= CreateWaitableTimer(IntPtr.Zero, false, "WaitableTimer"); //true

Console.WriteLine(
"Last Error = " + Marshal.GetLastWin32Error().ToString());

// Setting the timer

SetWaitableTimer(handle, ref liDueTime, 0, TimerComplete, IntPtr.Zero, true);
Console.WriteLine(
"Last Error = " + Marshal.GetLastWin32Error().ToString());

// Waiting for the timer to expire

if (WaitForSingleObject(handle, INFINITE) != 0)
{

Console.WriteLine(
"Last Error = " + Marshal.GetLastWin32Error().ToString());
}

else
{

Console.WriteLine(
"Timer expired @ " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
}

CloseHandle(handle);

// Raising event Timer Completed

//if (OnTimerCompleted != null)
//{

// // OnTimerCompleted();

//}
}

[DllImport(
"PowrProf.dll", ExactSpelling = true, SetLastError = true)]
public static extern bool SetSuspendState(bool Hibernate, bool ForceCritical, bool DisableWakeEvent);



private static void TimerCompleted()
{

Console.WriteLine(
"TimerCompleted()");

}


[DllImport(
"kernel32.dll")]
static extern IntPtr CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName);

[DllImport(
"kernel32.dll")]
static extern bool SetWaitableTimer(IntPtr hTimer, [In] ref System.Runtime.InteropServices.ComTypes.FILETIME ft, int lPeriod, TimerCompleteDelegate pfnCompletionRoutine, IntPtr pArgToCompletionRoutine, bool fResume);

[DllImport(
"kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern Int32 WaitForSingleObject(IntPtr Handle, uint Wait);

[DllImport(
"kernel32.dll")]
static extern bool CancelWaitableTimer(IntPtr hTimer);

[DllImport(
"kernel32", EntryPoint = "CloseHandle")]
private static extern IntPtr CloseHandle(IntPtr hObject);
}
}

 

MyPowerMgr.SetTimer(10);
MyPowerMgr.SetSuspendState(true, true, false);

 

 

 

 

posted @ 2010-06-12 11:29  chunchill  阅读(793)  评论(0)    收藏  举报