Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect shutdown in window service

i have a windows service that get user details and save the result into log text file. and, my problem is when i shut down or log off my system, i also would like to save the time that i down my system into that log file. but, i don't know how to do that.

I checked the winproc method to detect shutdown operation but i was not able to use it on window service, on googling found it can be used with forms only. how can we detect user have clicked shutdown or log off and do some action. so,please give me some idea or suggestion on that.

i have used it for logoff but on log entry is made when i logoff the system

  protected override void OnSessionChange(SessionChangeDescription changeDescription)
  {
     this.RequestAdditionalTime(250000); //gives a 25 second delay on Logoff
     if (changeDescription.Reason == SessionChangeReason.SessionLogoff)
     {
        // Add your save code here
        StreamWriter str = new StreamWriter("D:\\Log.txt", true);
        str.WriteLine("Service stoped due to " + changeDescription.Reason.ToString() + "on" + DateTime.Now.ToString());
        str.Close();
     }
     base.OnSessionChange(changeDescription);
 }
like image 902
deepu Avatar asked Mar 05 '11 06:03

deepu


1 Answers

For a shutdown, override the OnShutdown method:

protected override void OnShutdown()
{
    //your code here
    base.OnShutdown();
}

For a logoff:

First, add an event handler to Microsoft.Win32.SystemEvents.SessionEnded in the Service Constructor:

public MyService()
{
    InitializeComponent;
    Microsoft.Win32.SystemEvents.SessionEnded += new Microsoft.Win32.SessionEndedEventHandler(SystemEvents_SessionEnded);
}

Then add the handler:

void SystemEvents_SessionEnded(object sender, Microsoft.Win32.SessionEndedEventArgs e)
{
    //your code here
}

This should catch any ended session, including the console itself (the one running the services).

like image 120
MPelletier Avatar answered Oct 13 '22 01:10

MPelletier