0

I have written a simple windows service to perform some tasks related to PowerModelChanged . But I have no idea to use that. You guys considering my flowing code and give me some advice, please:

 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;
            }
        }
    }
Khai Le
  • 33
  • 4

1 Answers1

0

Try this (did not tested it, but it should be like this):

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

        }
    }
VDN
  • 717
  • 4
  • 12
  • @VND thanks for your answer, but it doesn't work correctly. Do you have any ways to handle that?! – Khai Le Mar 07 '16 at 10:18
  • @KhaiLe, can you clarify, what is incorrect, and how it is supposed to be? Did you receive any error messages? – VDN Mar 07 '16 at 10:54
  • Have a look at [this link](http://stackoverflow.com/questions/16593100/what-is-the-proper-way-to-have-a-windows-service-stop-and-start-gracefully-when) – VDN Mar 07 '16 at 11:06