Detecting/trapping the shutdiwn event

P

Paul Steele

Some time ago I tracked down the code for detecting the shutdown event
within a C# program. I tested it, it worked, and I moved on. However, I just
discovered that the code is no longer working, and I'm baffled. I've done
some more Google searches and have come up with the same thing. A portion of
the code is below. I call the HookSessionEnding routine in the Load event of
the main form, but the shutdown event code never fires. I'm baffled.

using Microsoft.Win32;

private void HookSessionEnding()
{
SystemEvents.SessionEnding += new
SessionEndingEventHandler(this.OnSessionEnding);
}

private void OnSessionEnding(object sender, SessionEndingEventArgs e )
{
MessageBox.Show("Shutting down");
}
 
P

Paul Steele

Paul Steele said:
Some time ago I tracked down the code for detecting the shutdown event
within a C# program. I tested it, it worked, and I moved on. However, I
just discovered that the code is no longer working, and I'm baffled. I've
done some more Google searches and have come up with the same thing. A
portion of the code is below. I call the HookSessionEnding routine in the
Load event of the main form, but the shutdown event code never fires. I'm
baffled.

using Microsoft.Win32;

private void HookSessionEnding()
{
SystemEvents.SessionEnding += new
SessionEndingEventHandler(this.OnSessionEnding);
}

private void OnSessionEnding(object sender, SessionEndingEventArgs e )
{
MessageBox.Show("Shutting down");
}

I've done some more Googling and have found part of my problem. I had a form
that sets e.Cancel to true and hides the form instead of actually closing
it. This works fine in normal operation but the e.cancel actually cancels
the shutdown event. Using the technique above the Window Closing event fires
before the OnSessionEnding event so it looks the same as a normal close
event. To get around the problem there's another way to trap SystemShutdown
using this code:

protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == 0x11)
{
//do whatever shutdown code you want to do
systemShutdown = true; //Use this in the Windows Closing event.
}
base.WndProc(ref m); //continue the regular shutdown process
}

Unfortunately even with this code the Windows Closing event *still* fires
first. This is the article that implies that it shouldn't:

http://msdn.microsoft.com/library/d...twin32systemeventsclasssessionendingtopic.asp

Has anyone else done this sort of thing successfully?
 
P

Paul Steele

Solved my own problem. The WndPrc override function has to go in each form
with special close operation...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top