Search code examples
c#windows-servicesc#-2.0system-shutdown

How cancel shutdown from a windows service C#


I have a windows service started (written in C# .net2.0).

I want to detect when the computer shutdown/reboot and cancel it. After the cancel I want do some actions and restart windows.

I have tried it, but it not working

using Microsoft.Win32;
partial class MyService: ServiceBase
{
    protected override void OnStart(string[] args)
    {
        SystemEvents.SessionEnding += new SessionEndingEventHandler(OnSessionEnding);
    }

    private void OnSessionEnding(object sender, SessionEndingEventArgs e)
    {
        e.Cancel = true;
        //Do some work...
    }
}

Another test:

partial class MyService: ServiceBase
{
    protected override void OnShutdown()
    {
        //Do some work...
        //base.OnShutdown();
    }
}

Solution

  • the solution was to detect the shutdown whith a winform : http://msdn.microsoft.com/fr-fr/library/microsoft.win32.systemevents.sessionending%28VS.80%29.aspx

    but Windows kill other process before i can detect it, so it's not the better solution!