Throwing out some WinForms candy to all the kiddies: Singleton Forms...
A large number of people constantly ask about having their form pop up in the same place over and over again and they usually want the same values to be there as well. If you use something like the ShowDialog() command on the same form over and over again, then everything works out fine, since closing the form doesn't dispose the form. However, if you tried the same thing just using the Show() command, then you'd get messed. Why? Because closing a non-dialog form really closes it. The stuff gets disposed and you can't recreate it. So what in the heck do you do?
Well, the answer is in the Closing event. If you tell the CancelEventArgs that you don't want to close, and you simply hide yourself then everything will be cool. This doesn't hurt the rest of the application either, because normally the ApplicationContext.MainForm points to the Form you started your application with. As soon as that MainForm exits, then the rest of the app will come down as well, regardless of what you say to the CancelEventArgs bad guy.
Now, let's develop this into a Singleton type experience, since after all, it would suck to have to keep an instance laying around now wouldn't it.
using System;
using System.ComponentModel;
using System.Windows.Forms;
public class SingletonForm : Form {
// Storage for our singleton
private static SingletonForm singleton = null;
// Bah, Designer support, so we can't prevent others
// from making our form by making this private. Foo!
public SingletonForm() {
}
// A single singleton instance with anti-close support
public static SingletonForm Current {
get {
if ( singleton == null ) {
singleton = new SingletonForm();
singleton.Closing +=
new CancelEventHandler(singleton.KeepAlive);
}
return singleton;
}
}
// Create loose singletons that have the same KeepAlive
// properties.
public static SingletonForm LooseSingleton() {
SingletonForm looseSingleton = new SingletonForm();
looseSingleton.Closing +=
new CancelEventHandler(looseSingleton.KeepAlive);
return looseSingleton;
}
// KeepAlive is only hooked for the singleton instance
private void KeepAlive(
object sender, CancelEventArgs e ) {
e.Cancel = true;
this.Hide();
}
}
PS > Whidbey has a better cancellation event that determines the reason for something being cancelled. Interacting with this extra information can help you better determine if you should exit or not. For instance, they tell you if the system is shutting down, if you are being cancelled by the TaskManager or whether a user is closing the form.