When a user clicks the X button on a form, how can I hide it instead of closing it?
I have tried this.hide()
in FormClosing
but it still closes the form.
To cancel the closure of a form, set the Cancel property of the CancelEventArgs passed to your event handler to true .
In order to totally close a C# application, including the hidden forms, you can use the following command in the event code of the “Exit” control: Application. Exit(); Application.
Press F5 to build and run the application. Click on the button in the main form to display the sub form. Now, when you press the button in the sub form, the form will be hidden.
Answer: To disable the Close button on an Access form, open the form in Design view. Under the View menu, select Properties. When the Properties window appears, set the "Close Button" property to No.
Like so:
private void MyForm_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing) { e.Cancel = true; Hide(); } }
(via Tim Huffman)
I've commented in a previous answer but thought I'd provide my own. Based on your question this code is similar to the top answer but adds the feature another mentions:
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing) { e.Cancel = true; Hide(); } }
If the user is simply hitting the X in the window, the form hides; if anything else such as Task Manager, Application.Exit()
, or Windows shutdown, the form is properly closed, since the return
statement would be executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With