DateTime timeStartUp;
DateTime timeShutdown;
public Form1()
{
InitializeComponent();
timer1.Tick += doShutdown;
}
/// <summary>
/// 收到服务端关机命令后调用这个方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnClose_Click(object sender, EventArgs e)
{
//if (timeStartUp == null)
//{
// MessageBox.Show("请先注册");
//}
doShutdown(null, null);
}
/// <summary>
/// 注册后拿到开关机时间后调用这个方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSet_Click(object sender, EventArgs e)
{
timeStartUp = DateTime.Today.AddDays(1).AddHours(8);//明天八点开机
timeShutdown = DateTime.Today.AddDays(1).AddHours(22);//今晚十点关机
timer1.Interval = (int)((timeShutdown - DateTime.Now).TotalMilliseconds);
timer1.Start();
}
private void doShutdown(object sender, EventArgs e)
{
SetWaitForWakeUpTime();
Application.Exit();
}
#region 具体实现核心
[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);
/// <summary>
/// 设置唤醒时间
/// </summary>
private void SetWaitForWakeUpTime()
{
long duetime = (long)((DateTime.Now - timeStartUp).TotalMilliseconds * 10000);
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;
Application.SetSuspendState(PowerState.Hibernate, true, false);
wh.WaitOne();
}
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
}
#endregion
开关机(休眠)设置
最新推荐文章于 2024-09-11 09:45:02 发布
这段代码展示了如何创建一个应用程序,该程序可以接收服务端的关机命令,并根据预设的时间进行电脑的自动开关机。用户可以设置明天早上8点开机和晚上10点关机,程序会通过Windows API调用来实现定时任务。当接收到关闭命令时,程序将进入休眠状态并在指定时间唤醒并退出。
摘要由CSDN通过智能技术生成