How can I prevent running multiple instances of a form?

Hi,

I have a button with the following code:

FormPrefs FP = new FormPrefs();
FP.Show();

How can I only allow one instance of FormPrefs to run?

Thanks.
EEssamAsked:
Who is Participating?
 
Jaime OlivaresConnect With a Mentor Software ArchitectCommented:
is it unique in the same application?
or maybe you want to avoid many application instances.

for first, you can do something like:

public class FormPrefs : Form
{
        private static FormPrefs UniqueForm = null;
       
        private FormPrefs()  // private constructor, don't allow to construct outside
        {
               // some tasks
        }
        public static void CreateOrShow()
        {
                if (UniqueForm == null)
                    UniqueForm = new FormPrefs();
                UniqueForm.Show();
        }
}

so you can use as:
FormPrefs.CraeteOrShow();
0
 
administradoresCommented:
If you don't use new, only one form will be showed.
0
 
administradoresConnect With a Mentor Commented:
But singletons is the way to go, sorry.

http://msdn2.microsoft.com/en-us/library/ms998558.aspx
0
 
administradoresCommented:
Also, if you use it as a mdichild form, you can add this line UniqueForm.BringToFront() after UniqueForm.Show() so the form will go to the top of your mdiontainer (form).
0
 
SameerJagdaleConnect With a Mentor Commented:
just create a static instance of form when your application loads and call show() / hide() methods.

Thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.