A common practice in WinForms programming is to keep only one instance of a certain form in the application. A new instance of that form is never created and shown. I have previously written a small note on this topic and gave a solution here which I personally don’t like.
In this post I am presenting a much better solution which is based on the singleton pattern. Rather than each time looking for the form in a list of opened forms I make the constructor private.
Let us start with the Form:
public sealed partial class ThirdForm : Form { }
The class is sealed so it cannot be inherited. We don’t want a child create an instance of this class multiple times.
Now add these members and methods to the class:
private static readonly ThirdForm MyInstance = new ThirdForm();
This is the sole instance of this form. And the private constructor to avoid multiple instances outside the class:
private ThirdForm()
{
InitializeComponent();
}
And the property to publish the sole instance:
public static ThirdForm OnlyInstance
{
get { return MyInstance; }
}
Another functionality that you might want to add to your Form is a new Show method. And you may also want to know whether the form was already opened or your opened it. Here is the answer to these questions. Add this code to your form class to Show() or Select() if already shown.
public new void Show() { if (IsShown) base.Show(); else { base.Show(); IsShown = true; } }
A variable IsShown of type bool is added to the form to record the current state.
private static bool IsShown = false;
static ThirdForm()
{
OnlyInstance.FormClosing += new FormClosingEventHandler(OnlyInstance_FormClosing);
}
private static void OnlyInstance_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
IsShown = false;
OnlyInstance.Hide();
}
The variable IsShown is set to false when the only instance of this form is closed. But remember its a singleton. We can’t let the only instance die so we catch FormClosing event and Hide() the form instead of closing it.
This solution looks elegant than looking for an opened form in an array but it has draw backs. You cannot catch the FormClosed event because it will never happen. The form is created only once so if your form is based on some volatile objects you will never see the change even if you close and open it again. May be I try to address these problems in another post some day. Spot On!
| Share this post : |

