Closing windows form
im developing windows application using c#. i want to close the application and show new form after clicking the button, i did it, but every time i cliecked the button, 开发者_高级运维it shows the another windows and when i going to task manager that form isntance still running. i want avoid that. i am using this.close() function to exit from the form.
Let's suppose you have Form1
and Form2
.
The code in Form1
should be something like this:
public partial class Form1 : Form
{
private Form2 _form2;
public Form1()
{
InitializeComponent();
_form2 = new Form2();
_form2.VisibleChanged += new EventHandler(_form2_VisibleChanged);
}
void _form2_VisibleChanged(object sender, EventArgs e)
{
if (!_form2.Visible)
Show();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
_form2.Show();
}
}
And in Form2
all you need to do is:
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
Hide();
}
Of course, you must suscribe to the event FormClosing
in Form2
, but if you do it through the designer (Form Properties
, clicking on Events
icon) just paste those two lines inside the method it creates)
What is this code doing?
In Form1
:
- Create a instance of
Form2
- In
Form1_FormClosing
method, all we do is hide the form instead of closing it when the user closes it, and showing the instance ofForm2
- Suscribe to the
VisibleChanged
event - When the event fires, if the instance of
Form2
isn't visible, thenForm1
appears.
In Form2
:
- The 2nd of the above steps, but without showing anything.
If you want to do it when you click on a button, all you need to do is do the same but on the Click
event on the button instead of the FormClosing
event.
精彩评论