. net -从代码设置电源选项
本文关键字:电源 选项 设置 代码 net | 更新日期: 2023-09-27 18:08:58
我想从c#中编写非常简单的代码-一个简单的2按钮应用程序,允许我改变盖子关闭时所采取的行动。从"睡觉"到"不行动",反之亦然。
我发现它以某种方式连接到WMI -但没有关于如何实现这一点的实际信息。
非常感谢您的帮助。
谢谢!
这是一个非常老的帖子,但令人惊讶的是,答案很难在其他地方找到。下面是我控制电源按钮的方法。希望它能帮助到一些人。虽然这篇文章的目的不同,但它帮助很大:
https://www.codeproject.com/Tips/490390/How-to-disable-the-Sleep-button-while-your-code-is这里是所有必需的导入。请注意,你有一个直流和交流值指数,这取决于平板电脑(在我的情况下)是否使用电池。
[DllImport("PowrProf.dll", CharSet = CharSet.Unicode)]
static extern UInt32 PowerWriteDCValueIndex(IntPtr RootPowerKey,
[MarshalAs(UnmanagedType.LPStruct)] Guid SchemeGuid,
[MarshalAs(UnmanagedType.LPStruct)] Guid SubGroupOfPowerSettingsGuid,
[MarshalAs(UnmanagedType.LPStruct)] Guid PowerSettingGuid,
int AcValueIndex);
[DllImport("PowrProf.dll", CharSet = CharSet.Unicode)]
static extern UInt32 PowerWriteACValueIndex(IntPtr RootPowerKey,
[MarshalAs(UnmanagedType.LPStruct)] Guid SchemeGuid,
[MarshalAs(UnmanagedType.LPStruct)] Guid SubGroupOfPowerSettingsGuid,
[MarshalAs(UnmanagedType.LPStruct)] Guid PowerSettingGuid,
int AcValueIndex);
[DllImport("PowrProf.dll", CharSet = CharSet.Unicode)]
static extern UInt32 PowerSetActiveScheme(IntPtr RootPowerKey,
[MarshalAs(UnmanagedType.LPStruct)] Guid SchemeGuid);
[DllImport("PowrProf.dll", CharSet = CharSet.Unicode)]
static extern UInt32 PowerGetActiveScheme(IntPtr UserPowerKey, out IntPtr ActivePolicyGuid);
static readonly Guid GUID_SYSTEM_BUTTON_SUBGROUP = new Guid("4f971e89-eebd-4455-a8de-9e59040e7347");
static readonly Guid GUID_POWERBUTTON = new Guid("7648efa3-dd9c-4e3e-b566-50f929386280");
static readonly Guid GUID_SLEEPBUTTON = new Guid("96996bc0-ad50-47ec-923b-6f41874dd9eb ");
你可以这样设置它:
IntPtr pActiveSchemeGuid;
var hr = PowerGetActiveScheme(IntPtr.Zero, out pActiveSchemeGuid);
Guid activeSchemeGuid = (Guid)Marshal.PtrToStructure(pActiveSchemeGuid, typeof(Guid));
hr = PowerWriteDCValueIndex(
IntPtr.Zero,
activeSchemeGuid,
GUID_SYSTEM_BUTTON_SUBGROUP,
GUID_POWERBUTTON,
0);
PowerSetActiveScheme(IntPtr.Zero, activeSchemeGuid); //This is necessary to apply the current scheme.
索引在这里定义https://msdn.microsoft.com/en-us/library/windows/hardware/mt608287(v=vs.85).aspx
就是这样。应该加入一些错误保护,但它效果很好。
看一下Windows API代码包,它是许多Windows API的包装。它包括电源管理API