Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimize on FormClose prevents computer shutdown

I have a simple Form-Based .NET application. In this I capture the FormClosing Event to prevent the closing of the application, instead I minimize it. The application should always be open. Here is the code I use:

private void Browser_FormClosing(object sender, FormClosingEventArgs e)
    {
       e.Cancel = true;
       this.WindowState = FormWindowState.Minimized;
       this.ShowInTaskbar = true;

    }

The problem now is that this prevents the computer from shuting down for users with non-admin rights. Anything I can do so that the computer is able to shut down and the user can`t close the application?

like image 315
Timo Haberkern Avatar asked Dec 21 '22 23:12

Timo Haberkern


2 Answers

Change it so that it doesn't always cancel but rather first look at e.CloseReason to see why the event is being called.

See the MSDN page for the CloseReason enumeration for valid values. It includes one called WindowsShutDown, and you might want to look at TaskManagerClosing as well (if someone is trying to close the app with the taskmanager, they probably really want it to close rather than just minimize).

like image 92
Hans Olsson Avatar answered Jan 03 '23 23:01

Hans Olsson


I found another solution for the problem. You can disable the closing button of the form, so your FormClosing event can be handled the default way

Code to disable the closing button:

protected override CreateParams CreateParams
    {
        get
        {
            CreateParams param = base.CreateParams;
            param.ClassStyle = param.ClassStyle | 0x200;
            return param;
        }
    }
like image 24
Timo Haberkern Avatar answered Jan 04 '23 00:01

Timo Haberkern