简体   繁体   中英

C# Windows Service Fails To Log Shutdown Event to Remote API

I am generating a C# windows service to log specific windows events. While most of them are fine (Logon/off, Lock/Unlock etc) I am having a few issues with the Windows power down type events. The code I am trying is as per the below (cribbed from other advice elsewhere).

For the Service:-

public Service()
        {
            InitializeComponent();
            SystemEvents.SessionEnded += new SessionEndedEventHandler(SystemEvents_SessionEnded);
            SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged);

        }

For SystemEvents_SessionEnded:-

void SystemEvents_SessionEnded(object sender, SessionEndedEventArgs e)
        {
            switch (e.Reason)
            {
                case SessionEndReasons.SystemShutdown:
                    eventType = 7;
                    break;
                case SessionEndReasons.Logoff:
                    eventType = 2;
                    break;
                default:
                    break;
            }

            \\Send eventType and current DateTime to remote API
        }

And for SystemEvents_PowerModeChanged

static void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
        {
            switch (e.Mode)
            {
                case PowerModes.Suspend:
                    eventType = 5;
                    break;
                case PowerModes.Resume:
                    eventType = 6;
                    break;
                default:
                    break;
            }

            \\Send eventType and current Datetime to API
        }

As the API is hosted externally to the local machine I am assuming that my service is reliant on others to send the data across the network? Any advice as to whether it is my code that is failing or whether I need better dependencies setting?

Thanks in advance.

The SessionEnded Docs say:

This event is only raised if the message pump is running. In a Windows service, unless a hidden form is used or the message pump has been started manually, this event will not be raised. For a code example that shows how to handle system events by using a hidden form in a Windows service, see the SystemEvents class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM