C# 如何将电脑休眠或进入睡眠模式

32

我想将我的系统置于睡眠或休眠状态,这是两个不同的选项。

我该如何使用API来实现这一目标?我不想使用Process,因为它不能让我选择所需的操作方法。


您可以在此链接中找到所有有关锁定PC、待机模式、休眠和注销的信息:http://www.geekpedia.com/tutorial177_Lock-Stand-By-Hibernate-and-Log-Off.html。 - Alex Ntousias
谢谢,我也需要锁定计算机的代码。 - Sandeep Bansal
1个回答

62
// Hibernate
Application.SetSuspendState(PowerState.Hibernate, true, true);
// Standby
Application.SetSuspendState(PowerState.Suspend, true, true);

或者,如果你喜欢使用系统调用:

[DllImport("Powrprof.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
public static extern bool SetSuspendState(bool hiberate, bool forceCritical, bool disableWakeEvent);

// Hibernate
SetSuspendState(true, true, true);
// Standby
SetSuspendState(false, true, true);

4
在Windows 8中如何做到这一点? - amr osama
@fre0n 当系统被调用时,它没有触发PowerModeChanged事件。 - prabhakaran
6
如果有人正在搜索这个并且不是使用WinForms,'Application'在System.Windows.Forms命名空间中。只需要导入引用,一切都会很完美地运行(至少在Win7上)。 - JsAndDotNet
@fre0n,你在“PowerState.Suspend”处缺少了一个逗号。 - Enis P. Aginić
2
@HockeyJ 我认为使用 P/Invoke / DLL 可能比导入整个 WinForms 命名空间更好;如果你需要在 WPF 解决方案中使用它。 - Danny Beckett
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接