views:

94

answers:

3

I'm writing a program which creates no forms at all until one is required. The problem is, it's preventing shutdown from continuing automatically. I've seen discussions about adding an if to form closing events to check if it's due to shutdown, but as I've said, my program is meant to have no forms at all until required.

Is there any event or some other method that will allow me to know when my program should be closing itself to allow for Windows to shut itself down automatically? And it's not multithreaded.

+1  A: 

You could always add a dummy form which you open minimized, with no icon on the taskbar - it won't have any visual impact, but will be sent the form closing event - where you could note the shutdown event, and presumably shut down/stop whatever else there is that your application is doing.

Damien_The_Unbeliever
+4  A: 

You can use the SystemEvents class, to "listen to" users logging out, or shutting down.

If I understand the documentation correctly (and a deep study with Reflector confirms this):

  • The systemevents will spawn a new thread that receives the messages from windows (it has its own messagepump).
  • When an event is received, your code will be called, from the new thread. You should be aware of this.
GvS
From the look of things, you still have to have a hidden form open (or have started the message pump manually) for this to work though.
Damien_The_Unbeliever
@Damien_The_Unbeliever - If that's true, it sounds silly.
a2h
@a2h - Maybe so, but look at example 2 on this page http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.aspx. Now, it's talking about a windows service. But it's only other example is a forms application that has a form open. And (from a bit of old school windows programming), knowing that these events are delivered via windows messages, it's not entirely unexpected.
Damien_The_Unbeliever
My mistake actually - it looks like SystemEvents will create a dummy message pump, if it can, so probably okay (but it can't do this within services).
Damien_The_Unbeliever
@Damien, was looking at same thing. Updated my answer.
GvS
+1  A: 

Handling the Microsoft.Win32.SystemEvents.SessionEnding event, and checking if it's an actual shutdown with System.Environment.HasShutdownStarted

Joachim VR