easy window problem

L

Lasse Edsvik

Hello

I have a button that opens a form like this:

private void button2_Click(object sender, System.EventArgs e)

{

Form2 myForm = new Form2();

myForm.Show();

}



problem is that it creates a new window for each click, i just want one
form, and if window exists i would like it to focus

TIA

/Lasse
 
D

Dmitriy Lapshin [C# / .NET MVP]

Hello Lasse,

Create the Form2 instance once and store the reference to it in a local
variable.
In the button2_Click handler, check whether Form2 is visible. If yes, just
Activate() it. If no, Show() it.

This is rather a way to explore things, not a complete solution. Should get
you started though.
 
?

=?ISO-8859-2?Q?Marcin_Grz=EAbski?=

Hi,
Hello

I have a button that opens a form like this:

private void button2_Click(object sender, System.EventArgs e)

{
Form2 myForm = new Form2();
myForm.Show();
}

problem is that it creates a new window for each click, i just want one
form, and if window exists i would like it to focus

Maybe you want show Form2 as a modal form (then main form will be locked)?
If "yes" then try :

myForm.ShowDialog()

.... other way was described by Dmitriy.

Regards

Marcin
 
M

Mike Peretz

Make your form a singleton by adding this code to it.

// member variable
private static Form2 m_frmInstance = new Form2()

// static memeber function
static public Instance()
{
get
{
return m_frmInstance;
}
}

// the rest of the form code goes here.

---------------------------------------------------------------

Your button click event, only has to do this

Form2.Instance.Show();

Hope this helps :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top