How to Disable Alt + F4 closing form?

后端 未结 11 1503
遇见更好的自我
遇见更好的自我 2020-11-29 21:23

What is the best way to disable Alt + F4 in a c# win form to prevent the user from closing the form?

I am using a form as a popup dialog to dis

相关标签:
11条回答
  • 2020-11-29 22:00

    I am using a form as a popup dialog to display a progress bar and I do not want the user to be able to close it.

    If the user is determined to close your app (and knowledgeable) enough to press alt+f4, they'll most likely also be knowledgeable enough to run task manager and kill your application instead.

    At least with alt+f4 your app can do a graceful shutdown, rather than just making people kill it. From experience, people killing your app means corrupt config files, broken databases, half-finished tasks that you can't resume, and many other painful things.

    At least prompt them with 'are you sure' rather than flat out preventing it.

    0 讨论(0)
  • 2020-11-29 22:04

    Hide close button on form by using the following in constructor of the form:

    this.ControlBox = false;
    
    0 讨论(0)
  • 2020-11-29 22:08

    You could handle the FormClosing event and set FormClosingEventArgs.Cancel to true.

    0 讨论(0)
  • 2020-11-29 22:08

    Would FormClosing be called even when you're programatically closing the window? If so, you'd probably want to add some code to allow the form to be closed when you're finished with it (instead of always canceling the operation)

    0 讨论(0)
  • 2020-11-29 22:11

    This is a hack to disable Alt + F4.

    private void test_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (this.ModifierKeys == Keys.Alt || this.ModifierKeys == Keys.F4) 
        { 
            e.Cancel = true; 
        }    
    }
    
    0 讨论(0)
提交回复
热议问题