You can use the
singleton design pattern[
^] for that. That pattern ensures that there's only one instance of a class.
example code for a WPF Window:
public sealed partial class SingleWindow : Window {
private static SingleWindow instance;
private bool isMainExit=false;
private SingleWindow() {
InitializeComponent();
App.Current.MainWindow.Closed+=new EventHandler(MainWindow_Closed);
}
public static SingleWindow Instance {
get {
if (instance == null) {
instance = new SingleWindow();
}
return instance;
}
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e) {
if (!isMainExit) {
this.Hide();
e.Cancel = true;
}
base.OnClosing(e);
}
private void MainWindow_Closed(object sender, EventArgs e) {
this.isMainExit=true;
this.Close();
}
}
After you close a form/window that form/window enters a state where you can't use it anymore (until the garbage collecter removes it entirely, I suppose). Therefore you need to check wether the form/window has been closed. Forms get disposed so you check for IsDisposed. I couldn't immediately find a similar mechanism for a WPF Window so I implemented a workaround. If anybody knows a more elegant solution, please correct me. :-)
edit: replaced WinForms code by WPF code