Question: 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();
    }
}

```

Answer: 
I wouldn't mess with this. Windows will treat your process like a hung process (unless you go direct to the Win32 API).

My suggestion would be to take note that you're being shutdown, and perhaps schedule the activities to happen on startup?

**UPDATE:**  

I think you're going to get stuck here, because your service won't know **why** Windows is being shutdown. You'll have an infinite loop:

* Windows shutdown fires.
* Service notices, aborts shutdown, launches app.
* User uses app to continue the shutdown.
* Window shutdown fires.
* Service notices......
* Etc.
`AbortSystemShutdown` might work:

<http://msdn.microsoft.com/en-us/library/aa376630%28VS.85%29.aspx>

Though I agree with Neil that it's probably not a good idea to do this.

Edit: Added sample code

```
using System.Runtime.InteropServices;

[DllImport("advapi32.dll", SetLastError=true)]
static extern bool AbortSystemShutdown(string lpMachineName);

if (!AbortSystemShutdown("localhost"))
{
    int err = Marshal.GetLastWin32Error();
}        

```