6

I have written a C# Windows Forms application, not a service (it is only used when the user is logged in and has a graphical user interface) that has a background thread running in an infinite loop.

When I try shutting down Windows (7) however, it tells me the program is preventing it from shutting down or logging off and asks me whether I want to force a shutdown.

Now, is there any possibility for my program to become aware (get a handler) of Windows trying to quit it or to log off?

So, what I need is to make the application realize when Windows tries to quit.

Thanks in advance.

EDIT: Thanks for the great advice! Is it in any way possible to use the idea with the form closing event if it has a CANCEL event handler?

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
arik
  • 28,170
  • 36
  • 100
  • 156
  • 1
    Can you quit your application by clicking on close button at the top right corner? If that's the case app shouldn't prevent the shutdown. Otherwise you need to handle that scenario first. – Sedat Kapanoglu Mar 23 '10 at 08:37

4 Answers4

12
public Form1()
{
    InitializeComponent();

    this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}

void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // Or any of the other reasons suitable for what you want to accomplish
    if (e.CloseReason == CloseReason.WindowsShutDown)
    {
        //Stop your infinite loop
    }
}
Don
  • 9,511
  • 4
  • 26
  • 25
  • Thanks. This really helped me. I removed the Cancel Handler and used this one, that way, only if it is Windows that closes the application it quits. – arik Mar 23 '10 at 12:44
5

You call that thread a "background thread" but does it have IsBackground = true; ?
The system will only stop a thread that does.

H H
  • 263,252
  • 30
  • 330
  • 514
2

I think Capture console exit C# should also be usable in your scenario.

Apart from that, maybe it is sufficient to set up your thread as background thread?

Community
  • 1
  • 1
flq
  • 22,247
  • 8
  • 55
  • 77
1

Take a look at the Microsoft.Win32.SystemEvents.SessionEnding event.

Stu Mackellar
  • 11,510
  • 1
  • 38
  • 59