How to dispose of variables in windows close button - c#

I have a windows forms application, where I have declared some static variables.
On the click of exit button, I have disposed of some datatable which i have declared static.
Many a times the user instead of clicking the exit button, will just exit the windows application by clicking the X button on the left corner top.
What should be done to ensure that even if the user clicks the X button, everything is disposed of properly.
Thanks
Regards
Hema

This question has some good descriptions of events that you can hook into to detect when a application is exiting.
Does Application.ApplicationExit event work to be notified of exit in non-Winforms apps?

Just add a delegate function to the Closing event of the form.
this.Closing += this.MyForm_Closing;
You can also use the Closed event of the form if you'd prefer it gets called after the form is closed.

You can add an event handler to dispose your variables when the form is closing.
private: System::Void myDialog_FormClosing(System::Object^ sender, System::Windows::Forms::FormClosingEventArgs^ e) {
// Dispose your static variables here
}

Related

Close form on deactivate breaks click event

I have a windows form in c# which should close when the user clicks anywhere outside of its bounds, eg:
form1.Deactivate += (o, e) => form1.Close();
My problem is, I would also like to catch the click event that caused the form to deactivate, but using the above code my mouse event handlers on the other forms in my application are never called.
For example, I have a click handler on a second visible form in my application:
form2.MouseClick += OnForm2Click
Normally OnForm2Click would get called fine if the user clicks on form2 when form1 is active, but with close-on-deactivate code above, OnForm2Click never gets called (this is a bit strange to me because double-click handlers are called just fine).
I cannot call form1.Close() from within OnForm2Click() as a solution because form2 has no reference to form1.
Thank you in advance for your solution.
You may solve your problem with a mouse hook. See:
Hooks Overview (Windows)

Why does FormClosing fire twice when calling Hide() in modal dialog?

We created a new form that we're showing via ShowDialog and added a "Cancel" button to it. Here's how we're opening the form from its parent:
// _modalForm is a class-level instance of our ModalForm class
var result = _modalForm.ShowDialog(this);
MessageBox.Show(result.ToString());
Here's the cancel button's Click event handler in ModalForm.
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
In our FormClosing event, we have this code (based on this answer).
private void ModalForm_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
Hide();
_parentForm.RefreshData();
}
Surprisingly, when we click the "Cancel" button (or use the "X" button at the top of the form), the FormClosing event is raised twice. Both times the CloseReason is UserClosing.
I double checked to make sure InitializeComponent isn't call twice and that we only subscribe to the event once. btnCancel is not set at the CancelButton property for the form. It also doesn't have DialogResult set in the designer. When I check the return value of ShowDialog though, it is set to DialogResult.Cancel.
Changing btnCancel_Click to just be DialogResult = DialogResult.Cancel instead of Close() and doing nothing except _parentForm.Refresh() in the FormClosing event fixes the issue of the event getting raised twice.
Does anyone know why in this particular scenario the FormClosing event gets raised twice?
That's because hiding a modal form will cause it to close with DialogResult.Cancel as dialog result. So if you call this.Hide() in FormClosing event, the event will be raised again.
Imagine if it didn't close the form, your application had been blocked by a hidden modal form!
Note: The answer describes about the reason of raising the event twice. But as described here and others mentioned, For modal forms (which you showed using ShowDialog), the Dispose method will not be called and the form exists after closing and you can use its properties to get some data or you can show it again. So you don't need to call hide method.
For more information take a look at: Do I need to Dispose a Form after the Form got Closed?
The workaround you mention is unnecessary, because modal dialogs are not disposed when closed. They are designed to keep their data after being closed (since it is required by the caller of the modal dialog), and to be reused as needed.
Just let it close properly. It causes no harm to a modal dialog :)
Note that this also means that unlike normal forms, you must dispose of modal dialogs manually if they are not persistent. In your scenario, this most likely means you'd want to dispose of the dialog when the parent form is disposed (this happens automatically if you added the dialog as a component, but needs to be done manually if you create it yourself).

Invoking several methods after ordering the program closed

I've got a WinForm Application that connects via Net.Sockets to another program.
When it gets closed per X or ALT+F4 or whatever, several routines should be processed and I need to keep the network connection until they're done.
I thought an Application.ApplicationExit Handler would do the trick, but as soon as I give the order the network connection is dead. Other important stuff can't be done.
My Form is closed instantaneously too, and I need that one a little longer.
Is Application.ApplicationExit the right tool for the job?
I put that in my Form Class that App.Runs from the Main method which is located in a different class.
You could use the Closing event of the form. It is called before the form is closed.
If you are having an open window, there are the event-handler Closing and Closed. The Closing-event is fired as soon as you click 'X', for example. Inside the method you can even decide, whether to close the window or not.
Provide an event-handler like
private void Form1_Closing(object sender, FormClosingEventArgs e){
// persist until everything is done
}
and associate it with the event
Form1.Closing += Form1_Closing;
See MSDN for documentation.

To close C# Forms Application

I have 2 forms ...when i start the application..and use the close "X" from the title bar the entire application closes...now when i select an option from the 1st form in my case it is a button "ADD" as its a phonebook application..it goes to the 2nd form as i have used 1stform.hide() and 2ndform.show()...now when i do "X" from the title bar it doesnt shutdown completely as the 1stform is not closed....how to program it in such a way tht any stage the entire application should close
Your first form is set as the startup form. That means whenever it gets closed, your entire application is closed. And conversely, your application does not close until it gets closed. So when you hide the startup form and show the second form, the user closing the second form does not trigger your application closing because they have only closed a secondary, non-modal dialog.
I recommend changing your design so that the startup form is also the main form of your application. No sense trying to work around built-in functionality that can actually be useful. You want the application to quit when the main form is closed, no matter what other child forms are opened.
But the quick-and-dirty solution in your case is to make a call to Application.Exit. That will close all of the currently open forms and quit your application immediately. As I said just above, I don't so much recommend this approach because having to call Application.Exit from every form's FormClosed event handler is a sign that something has gone seriously wrong in your design.
If the single startup form paradigm doesn't work out for you, you should look into taking matters into your own hands and customizing the Main method in your Program.cs source file. See the answers given to this related question for some ideas on how that might work for you.
What you can do is to use the Form's FormClosing event, and add the following code:
Application.Exit();
This will stop the entire application, and close all windows. However, if a background thread is running, the process itself will survive. In this case you can use:
Environment.Exit();
Add a Application.Exit on every forms's Closing event
like this:
Create an closing event handler first
private void Form_ClosingEventhandler()(object sender, CancelEventArgs e)
{
//Perform any processing if required like saving user settings or cleaning resources
Application.Exit();
}
then bind this event to any form you create.
//Where you create new form and show it.
Form1 frm= new Form1();
//set other properties
frm.Closing += new EventHandler(Form_ClosingEventhandler);
Form2 frm2= new Form2();
//set other properties
frm2.Closing += new EventHandler(Form_ClosingEventhandler);
Surely you don't want to shut down the entire application after the user adds a phone number? You just need to make sure that your main window becomes visible again. Write that like this:
private void AddButton_Click(object sender, EventArgs e) {
var frm = new AddPhoneNumber();
frm.StartPosition = FormStartPosition.Manual;
frm.Location = this.Location;
frm.Size = this.Size; // optional
frm.FormClosing += delegate { this.Show(); };
frm.Show();
this.Hide();
}

Button with an X at the upper-right corner of the form, how to catch this event # C#

Which event is fired when I close a form with the X button?
I want the event that fires only when the X button is pressed; I know that there is a FormClosing event, but the problem is that it fires each time when form is closed...
It also fires when frm.close() executes, and I don't want that to happen.
You can check the CloseReason property of FormClosingEventArgs parameter. It is CloseReason.UserClosing when you click the 'X' button.
There is no specific event wired up to the X in the upper right hand corner of the form.
Instead, use the form's FormClosing event. It has a Cancel parameter which you can set to true if you don't want the form to close. This allows you to check for form closings that take place via other means, such as the OK button being clicked.
As Robert stated there is no specific event associated with 'X', but you basically have two options which can be used to solve your probelm.
(i) Form Closing - This event occurs when you click the 'X', but before closing the form. So you can use this event handler to do some stuff just before closing the form. For example, you can stop the form from being closed / destroyed by using e.Cancel();
(ii) Form Closed - This event occurs when the form is closed.
Regards
I use the form's OnClosing event, which can be cancelled as well.

Categories