Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide form instead of closing when close button clicked

Tags:

c#

.net

winforms

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.

like image 276
iTEgg Avatar asked Jan 07 '10 16:01

iTEgg


People also ask

How do I stop a windows form from closing?

To cancel the closure of a form, set the Cancel property of the CancelEventArgs passed to your event handler to true .

How do you close a hidden form?

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.

How hide windows form in C#?

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.

How do I disable the close button?

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.


2 Answers

Like so:

private void MyForm_FormClosing(object sender, FormClosingEventArgs e) {     if (e.CloseReason == CloseReason.UserClosing)      {         e.Cancel = true;         Hide();     } } 

(via Tim Huffman)

like image 123
Alex Avatar answered Sep 20 '22 16:09

Alex


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.

like image 21
LizB Avatar answered Sep 19 '22 16:09

LizB