Reputation: 641
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.
Upvotes: 0
Views: 2511
Reputation: 29863
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
:
Form2
Form1_FormClosing
method, all we do is hide the form instead of closing it when the user closes it, and showing the instance of Form2
VisibleChanged
event Form2
isn't visible, then Form1
appears. In Form2
:
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.
Upvotes: 2