Reputation: 89
Whenever I need to show another Form, I always instantiate a new Form Object to show another Form (then hiding the current form).
/*Code in Form1*/
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Show();
this.Hide();
}
After I instantiated and showed the second Form, I want to dispose the previous form (to free up some memory usage) but it is not working on the main context form.
However, the Dispose() method is working on other WinForms which is not the main context form.
/*Code in Form2*/
private void button1_Click(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
frm1.Show();
this.Dispose();
}
Is it possible to instantiate a Form Object once only, then eventually to call/show it whenever I need it?
Upvotes: 0
Views: 111
Reputation: 12557
I would create a class called "FormHandler"
this may have a method like
here some prototype code (not tested)
public static class FormHandler
{
private static readonly Dictionary<string,Form> Instances = new Dictionary<string,Form>();
public TForm CreateFrom<TForm>()
{
string typeName = typeof(TForm).FullName;
if(Instances.ContainsKey(typeName))
{
return Instances[typeName]
}
else
{
// Create Instace with Activator.CreateInstance,
// and bind the dispose event to remove the form from the collection
// on dispose . Also make sure that you unbind the dispose Event
[...]
}
}
Now the buttonClick would just call
FormHandler.CreateForm<Form2>().Show();
with seperating the code to a new class you can avoid copy and paste in all buttons
Upvotes: 0
Reputation: 10612
/*Code in Form1*/
Form2 frm2; // --> Inside the class
private void button1_Click(object sender, EventArgs e)
{
if (frm2 == null)frm2 = new Form2();
frm2.Show();
this.Hide();
}
.
/*Code in Form2*/
Form1 frm1;
//Constructor
public Form2(Form1 frm)
{
frm1= frm;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
frm1.Show();
this.Hide();
}
Upvotes: 1
Reputation: 156918
You can start your own ApplicationContext
, and pass that to every form you want to make the MainForm
. You shouldn't keep forms in memory and open and close them at will in my opinion. This could lead to potential memory leaks.
ApplicationContext ac = new ApplicationContext();
ac.MainForm = new Form1(ac);
Application.Run(ac);
(You will put this in the place of Application.Run(new Form1());
)
In Form1
, when you want to make Form2
the main form:
ac.MainForm = new Form2(ac);
this.Close();
This way, the form can be disposed (since you called Close()
and used Show
it will automatically dispose) and memory can be cleared. The instance of Form2
will be the new main form.
Upvotes: 1