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.
Finaly I abort the idea of detect and cancel windows shutdown/reboot, 
But now I **want detect only "shutdown -r -t xx"** ! 

*Please note the operating system where is running the programme is Windows XP.*

I have try it, but I have no ExitCode with WindowsXP:

```
Process process = new Process();

do
{
    process.StartInfo.FileName = "shutdown.exe";
    process.StartInfo.Arguments = "/a";
    process.Start();
    process.WaitForExit();
    MessageBox.Show(string.Format("ExitCode={0}",process.ExitCode));
    Thread.Sleep(1000);
}
while (process.ExitCode != 0) ;

```