Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Windows application prevents Windows from shutting down / logging off

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?

like image 802
arik Avatar asked Dec 02 '22 05:12

arik


2 Answers

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
    }
}
like image 161
Don Avatar answered Dec 22 '22 19:12

Don


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

like image 23
Henk Holterman Avatar answered Dec 22 '22 19:12

Henk Holterman