在 C# 中检测系统从睡眠中唤醒的事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18206183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:32:17  来源:igfitidea点击:

Event to detect System wake up from sleep in C#

c#windowsevents

提问by Pankaj

I need to detect the system power state mode. To be precise, I need an event which fires up when windows 7 wakes up from sleep. I am already using:

我需要检测系统电源状态模式。准确地说,我需要一个在 Windows 7 从睡眠中醒来时触发的事件。我已经在使用:

SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;

But the problem with this event is that it is raised up four times: possibly when computer goes into sleep mode and after computer wakes up. I want an event which is raised at computer wake up only. Is there any event for this?

但是这个事件的问题是它被引发了四次:可能是在计算机进入睡眠模式和计算机唤醒之后。我想要一个仅在计算机唤醒时引发的事件。有什么活动吗?

采纳答案by Marcus

SystemEvents.PowerModeChanged += OnPowerChange;

private void OnPowerChange(object s, PowerModeChangedEventArgs e) 
{
    switch ( e.Mode ) 
    {
        case PowerModes.Resume: 
        break;
        case PowerModes.Suspend:
        break;
    }
}

You should probably read this: http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.powermodechanged.aspx

您可能应该阅读以下内容:http: //msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.powermodechanged.aspx

回答by Moo-Juice

You need to inspect the Modeproperty of the PowerModeChangedEventArgsthat is passed to the event.

您需要检查传递给事件的Mode属性PowerModeChangedEventArgs

From MSDN:

来自 MSDN:

  • ResumeThe operating system is about to resume from a suspended state.

  • StatusChangeA power mode status notification event has been raised by the operating system. This might indicate a weak or charging battery, a transition between AC power and battery, or another change in the status of the system power supply.

  • SuspendThe operating system is about to be suspended.

  • Resume操作系统即将从挂起状态恢复。

  • StatusChange操作系统已引发电源模式状态通知事件。这可能表示电池电量不足或正在充电、交流电源和电池之间的转换或系统电源状态的其他变化。

  • Suspend操作系统即将暂停。

回答by habib

SystemEvents.PowerModeChanged += OnPowerModeChange;
private void OnPoweModerChange(object s, PowerModeChangedEventArgs e)
{
  if(e.Mode==PowerModes.Suspend)
  {
    //Apply your operation
  }
}

Use this code to do your job

使用此代码来完成您的工作