How to set a Winform window to only open one instance.
To ensure only one instance of a Winform window can be opened, you can implement the singleton pattern.
- Firstly, add a private static member variable in the class of the form to store the unique instance.
private static Form1 instance;
- Then, set the constructor of the window to private to prevent instances from being created directly using the new keyword.
private Form1()
{
InitializeComponent();
}
- Next, create a public static method to obtain the unique instance of the form. Within this method, firstly check if an instance already exists; if it doesn’t, create an instance and store it in a static variable, then return the instance.
public static Form1 GetInstance()
{
if (instance == null || instance.IsDisposed)
{
instance = new Form1();
}
return instance;
}
- Finally, call the GetInstance method to obtain the instance of the form and display it where needed.
Form1 form = Form1.GetInstance();
form.Show();
This way, no matter how many times the GetInstance method is called, it will only return the same window instance, ensuring that only one window can be opened.