Click here to Skip to main content
15,886,773 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello Seniors,

This is my first post to the community.

I am new to c# and want to know if its possible to open only one instance of a form?

I mean if the form is already open then it should be activated instead of opening new instance of it.

Thanks in advance.

[Replaced C++ tag with C# - Rajesh]
Posted
Updated 7-Dec-10 21:46pm
v3
Comments
Dalek Dave 8-Dec-10 3:46am    
Edited for Grammar and Readability.
Manfred Rudolf Bihy 8-Dec-10 7:13am    
Ok I got it right this time. I changed my answer so please look there. Thanks for pointing that out, I totally forgot that closing a form implicitely does a Dispose().

Please use the singleton pattern for that. Short summary:

Make class constructor private.

Have a public static function like GetInstance(...).
Function will return content of variable instance if not null
else it will instantiate the class and assign that to the variable instance.

Modification:
Sorry! Your're right of course, closing the form will dispose it and it can't be used anymore. So I added an event handler that just hides the form when you close it (also works by calling Close() method of form):

C#
namespace Singleton
{
    public partial class Form1 : Form
    {
        private static Form1 instance;
        private Form1()
        {
            InitializeComponent();
            Form1.instance = this;
            this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
        }

        void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true; //This prevents form from really closing
            ((Form1)sender).Hide();
        }

        public static Form1 GetInstance()
        {
            if (instance == null)
                return new Form1();
            else
               return instance;
        }
    }
}


That works now. In another form I have a button with click event handler:

C#
private void button1_Click(object sender, EventArgs e)
{
    Form1 form = Form1.GetInstance();
    form.Show();
}

Now you can "close" Form1 as often as you want and when button is pressed it reappears and it's always the same instance.


Cheers


Manfred
 
Share this answer
 
v3
Comments
Dalek Dave 8-Dec-10 3:47am    
Good Call.
asudesai 8-Dec-10 6:33am    
can you please elaborate on your solution sir ? as i am sitting here creating my very first project in c#. thanks in advance.
Espen Harlinn 17-Mar-11 10:05am    
A 5 here, and ...
Hi,

Looks like you didn't do a Google search: http://forums.techpowerup.com/showthread.php?t=34685[^]
 
Share this answer
 
Comments
Dalek Dave 8-Dec-10 3:47am    
Harsh! He is a n00b
Rajesh R Subramanian 8-Dec-10 3:54am    
Hey, but Google's for everyone. :)
[no name] 24-Jun-12 14:26pm    
This is the kind of answer, you make and you say you are MVP, the question has been asked and you were expected to reply with answer, if someone can do google search why code project is required.
Rajesh R Subramanian 24-Jun-12 14:38pm    
It looks like you don't have a life at all. People over here may not be particularly feeling like helping those ones who are too lazy to run a Google search.

BTW, I don't "say" I am an MVP. I have been awarded, based on my contributions to this site. So, try to get a life, or screw yourself over. Don't bother me.
You could also create a modeless form, and show/hide it as necessary.

C#
public class MyClass
{
    MyForm form = null;

    // to show the form
    private void ShowForm()
    {
        if (form == null)
        {
            form = new MyForm();
        }
        form.Show();
    }

    // to hide the form
    private void HideForm()
    {
        if (form != null)
        {
            form.Hide();
        }
    }
}
 
Share this answer
 
v2
Comments
Manfred Rudolf Bihy 8-Dec-10 10:43am    
Hi John, what keeps one from creating more than one instance of MyForm()? Am I missing something?
Hi asudesai,

If you are using winform and mdi form to open then let do these steps.

VB
If Me.MdiChildren.Length > 0 Then           
            
                For Each frmChild As Form In Me.MdiChildren
                    If frmChild.Visible = True Then
                        frmChild.Close()
                        Exit For
                    End If
                Next
                'Code to Open form 
            
        Else
            'Code to Open form 
End If
 
Share this answer
 
Comments
Manfred Rudolf Bihy 8-Dec-10 7:29am    
My vote of 1: Sorry vivekse, but OP wanted only a single instance of his form and not closing it and then reopening it. Please reread his question carefully.
sacraj 13-Apr-11 23:48pm    
I accept your answer It works fine for Forms, If you do not mind could you give a solution for opening a database connection only once and use it through the application using singleton method. Th e data base SQL-Server.
Manfred Rudolf Bihy 14-Apr-11 4:29am    
Do you mean my solution or vivekse's. You replied to my comment to vivekse's solution so I'm not sure which solution you're talking about. Please clarify, thank you!

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