如何在Windows服务应用程序中使用PowerModelChanged事件?

时间:2016-03-07 09:39:40

标签: c# windows service

我编写了一个简单的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;
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

尝试这个(没有测试过,但它应该是这样的):

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);
        }

        }
    }