修改PC进入睡眠的时间(win10,c#)

2019-07-14 01:11发布

最近项目中需求一个修改电脑进入睡眠时间的功能,如图要把接通电源时间改为2个小时,并且把恢复默认设置后也保持2个小时,重要需求就是这个,那么我们来看如何实现的。以下为代码using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; namespace TosBalanACSleepService { public partial class Service1 : ServiceBase { [DllImport("PowrProf.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern uint PowerWriteACDefaultIndex( IntPtr RootSystemPowerKey, ref Guid SchemePersonalityGuid, ref Guid SubGroupOfPowerSettionsGuid, ref Guid PowerSettingGuid, long DefultAcindex); [DllImport("PowrProf.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern uint PowerWriteACValueIndex( IntPtr RootSystemPowerKey, ref Guid SchemePersonalityGuid, ref Guid SubGroupOfPowerSettionsGuid, ref Guid PowerSettingGuid, long DefultAcindex); public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { Guid GUID_TYPICAL_POWER_SAVINGS = new Guid("381b4222-f694-41f0-9685-ff5bb260df2e"); Guid GUID_SLEEP_SUBGROUP = new Guid("238C9FA8-0AAD-41ED-83F4-97BE242C8F20"); Guid GUID_STANDBY_TIMEOUT = new Guid("29F6C1DB-86DA-48C5-9FDB-F2B67B1F44DA"); long value = 7200; try { PowerWriteACDefaultIndex(IntPtr.Zero, ref GUID_TYPICAL_POWER_SAVINGS, ref GUID_SLEEP_SUBGROUP, ref GUID_STANDBY_TIMEOUT, value); PowerWriteACValueIndex(IntPtr.Zero, ref GUID_TYPICAL_POWER_SAVINGS, ref GUID_SLEEP_SUBGROUP, ref GUID_STANDBY_TIMEOUT, value); /* RegistryKey key = Registry.LocalMachine; RegistryKey Sleepsoftware = key.OpenSubKey(@"SYSTEMCurrentControlSetControlPowerUserDefaultPowerSchemes381b4222-f694-41f0-9685-ff5bb260df2e238c9fa8-0aad-41ed-83f4-97be242c8f2029f6c1db-86da-48c5-9fdb-f2b67b1f44da", true); Sleepsoftware.SetValue("ACSettingIndex", 7200);*///若是改不了恢复默认设置的睡眠时间,请去掉注释改注册表 } catch { } } protected override void OnStop() { } } }
这个就是代码实现的过程,其实按功能来说不用改注册表也能实现,为什么改注册表是应因为我们内部有一个其他组件之前改过睡眠时间,之后再改就改不掉了,研究过后决定改注册表,并且用最高权限来做,所以你可以看到我这段实现是写在服务中的,运行时安装此服务并开启,之后再然后马上卸载掉来完成此功能。