Please use the singleton pattern for that. Short summary:
Make class constructor private.
Have a public static function like GetInstance(...).
Function will return content of variable instance if not null
else it will instantiate the class and assign that to the variable instance.
Modification:
Sorry! Your're right of course, closing the form will dispose it and it can't be used anymore. So I added an event handler that just hides the form when you close it (also works by calling Close() method of form):
namespace Singleton
{
public partial class Form1 : Form
{
private static Form1 instance;
private Form1()
{
InitializeComponent();
Form1.instance = this;
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
((Form1)sender).Hide();
}
public static Form1 GetInstance()
{
if (instance == null)
return new Form1();
else
return instance;
}
}
}
That works now. In another form I have a button with click event handler:
private void button1_Click(object sender, EventArgs e)
{
Form1 form = Form1.GetInstance();
form.Show();
}
Now you can "close" Form1 as often as you want and when button is pressed it reappears and it's always the same instance.
Cheers
Manfred