Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在windows服务应用程序中使用PowerModelChanged事件?_C#_Windows_Service - Fatal编程技术网

C# 如何在windows服务应用程序中使用PowerModelChanged事件?

C# 如何在windows服务应用程序中使用PowerModelChanged事件?,c#,windows,service,C#,Windows,Service,我编写了一个简单的windows服务来执行一些与PowerModelChanged相关的任务。但我不知道该怎么用。你们考虑我的流动代码并给我一些建议,请: public partial class Service : ServiceBase { public Service() { InitializeComponent(); this.CanHandlePowerEvent = true;

我编写了一个简单的windows服务来执行一些与PowerModelChanged相关的任务。但我不知道该怎么用。你们考虑我的流动代码并给我一些建议,请:

 public partial class Service : ServiceBase
    {
        public Service()
        {
            InitializeComponent();
            this.CanHandlePowerEvent = true;
            SystemEvents.PowerModeChanged += PowerModeChanged;
        }

        protected override void OnStart(string[] args)
        {
            Library.WriteUserLog("ON");
        }

        protected override void OnStop()
        {
            Library.WriteUserLog("OFF");
        }

        // Write log when user either logon or logoff
        public void PowerModeChanged(object sender, PowerModeChangedEventArgs e)
        {
            switch (e.Mode)
            {
                case PowerModes.Resume:
                    Library.WriteUserLog("ON");
                    break;
                case PowerModes.Suspend:
                    Library.WriteUserLog("OFF");
                    break;
            }
        }
    }
试试这个(没有测试,但应该是这样的):


@VND感谢您的回答,但它不能正常工作。你有办法处理吗@凯勒,你能澄清一下,什么是不正确的,应该是怎样的吗?您是否收到任何错误消息?请查看
public partial class Service : ServiceBase
    {
        public Service()
        {
            InitializeComponent();
            this.CanHandlePowerEvent = true;
        }

        protected override void OnStart(string[] args)
        {
            Library.WriteUserLog("ON");
        }

        protected override void OnStop()
        {
            Library.WriteUserLog("OFF");
        }

        protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
        {
            switch (powerStatus)
            {
                case PowerBroadcastStatus.ResumeSuspend:
                    Library.WriteUserLog("ON");
                    break;
                case PowerBroadcastStatus.Suspend:
                    Library.WriteUserLog("OFF");
                    break;
                    // other statuses....
            }
            return base.OnPowerEvent(powerStatus);
        }

        }
    }