Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have a C# windows Form application that creates multiple instances of the same window, when I double click the shortcut, but I only want one single instance of the window.
Can someone please tell me how to accomplish this?
Thanks.

What I have tried:

I tried what was described in this video:
The Singleton Pattern - YouTube[^]
Posted
Updated 7-Jan-17 9:06am

You could use a singleton pattern to ensure that only one instance exists, but I think that it would be easier just to loop through Application.OpenForms Property (System.Windows.Forms)[^].

Loop through the collection, check if the form exists and if it does, activate it, if it doesn't, create it.

[EDIT]
An example loop to iterate through the forms
C#
bool formOpen = false;

foreach (Form form in Application.OpenForms) {
   if (form.Name == "Form1") {
      formOpen = true;
      break;
   }
}
if (formOpen) {
   MessageBox.Show("Form is already open");
} else {
   MessageBox.Show("Form is not open");
}
 
Share this answer
 
v3
Comments
Member 10850253 7-Jan-17 9:37am    
I tried comparing the Application.OpenForms.Count==0, and if that was true, then I ran the application, but that doesn't work, and I was wondering if you could tell me where do I need to use this property?
Wendelius 7-Jan-17 9:44am    
I'm sorry but I don't fully understand. Are the forms in different applications?

In other words are you trying to prevent an application from running if it's already executing or are you trying to prevent a form from opening twice inside a single application?
Member 10850253 7-Jan-17 9:53am    
yes
Wendelius 7-Jan-17 9:55am    
Which one is yes? Only one application or only one form inside an application?
Member 10850253 7-Jan-17 9:56am    
one form in an application
I'd suggest to read past answers[^].
 
Share this answer
 
I did this in program.cs
C#
public static bool bf = false;
        static void Main()
        {
            foreach (Form form in Application.OpenForms)
            {
                if (form.Name == "BatteryMonitorForm")
                {
                    bf = true;
                    break;
                }
            }
            if (!bf)
            {
                //Application.EnableVisualStyles();

                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new BatteryMonitorForm());
            }
            else { }
            
            }
            }      

And it still doesn't work, I don't know what to do.
Can you please help?
Thanks.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900