tags:

views:

400

answers:

5

How to avoid multiple instances of windows form in c# ?? i want only one instance of the form running. Because there are chances of opening the same form from many pages of my application.

+8  A: 

implement the Singleton pattern

an example: CodeProject: Simple Singleton Forms (ok, it's in VB.NET, but just to give you a clue)

Natrium
make sure that you overload FormClosing and check the close reason if the reason is user then hide the form and set cancel = true
Petoj
+1 For Singleton. It's often overlooked.
Kyle Rozendo
A: 

You can check the existing processes prior to opening the form:

using System.Diagnostics;

bool ApplicationAlreadyStarted()
{
  return Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length == 0;
}

I don't know if the GetProcessesByName method is affected by UAC or other security measures.

David Andres
If you read the question it's not about a singleton application, it's about a form within the app that can be opened from many places and only wanting one instance.
Timothy Walters
+1  A: 

Yes, it has singleton pattern,

Code to create a singleton object,

public partial class Form2 : Form
{
 .....
 private static Form2 inst;
 public static Form2  GetForm
 {
   get
    {
     if (inst == null || inst.IsDisposed)
         inst = new Form2();
     return inst;
     }
 }
 ....
}

Invoke/Show this form,

Form2.GetForm.Show();
adatapost
A: 

Singletons are not object-oriented. They are simply the object version of global variables. What you can do is to make the constructor of the Form class private, so nobody can accidentally create one of these. Then call in reflection, convert the ctor to public and make sure you create one and only one instance of it.

That's a very bad idea! Take a look at the 'static class' features of C#, or just use the singleton pattern.
Timothy Walters
A: 

If your system has the possibility of showing the same type of form for different instance data then you could create a checking system that iterates all existing open forms, looking for a unique instance data identifier and then re-display any found form.

e.g. having a form class 'CustomerDetails' which contains a public property 'CustomerUniqueID':

foreach(Form f in CurrentlyDisplayedForms)
{
    CustomerDetails details = f as CustomerDetails;
    if((details != null) && (details.CustomerUniqueUD == myCustomerID))
    {
        details.BringToFront();
    }
    else
    {
        CustomerDetails newDetail = new CustomerDetails(myCustomerID);
    }
}

We also use the same mechanism to automatically force refreshes of data binding where a customer's data has been edited and saved.

Dr Herbie