ImonBayazid
ImonBayazid

Reputation: 1096

if called window is already running then close it and run newly called window

In my app in several time i have to call a window(class). the work of this window is to show the meaning of a word.when i again call that window a new window shows but the previous one also shows. I have two form named form1,form2.

Form1 is like that:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    { 
         string a = textBox1.Text;
         Form2 s = new Form2(a);// it will be called as many time as i click
         s.Show();
    }
}

Form2 is like that:

public partial class Form2 : Form
{
    public Form2(string s)
    {
        InitializeComponent();
        label1.Text = s;
    }
}

what i want is that inside form1 if i call form2 it shows but if i call form2 again the previous form2 window will be closed automatically and new form2 window will be shown instead of previous one. How can i do that????

Upvotes: 0

Views: 101

Answers (2)

VahidNaderi
VahidNaderi

Reputation: 2488

I think you should consider using singleton pattern.

You can implement it like this:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    { 
         string a = textBox1.Text;
         Form2.ShowMeaning(a);// it will be called as many time as you click
    }
}

and Form2

public partial class Form2 : Form
{
    private static readonly Form2 _formInstance = new Form2();

    private Form2()
    {
        InitializeComponent();
    }

    private void LoadMeaning(string s)
    {
        label1.Text = s;
    }

    //Override method to prevent disposing the form when closing.
    protected override void OnClosing(CancelEventArgs e)
    {
        e.Cancel = true;
        this.Hide();
    }

    public static void ShowMeaning(string s)
    {
        _formInstance.LoadMeaning(s);
        _formInstance.Show();
    }
}

Hope it helps.

Upvotes: 0

Idle_Mind
Idle_Mind

Reputation: 39122

Here's an example of storing the Form2 reference at class level, as mentioned by the others already:

public partial class Form1 : Form
{

    private Form2 f2 = null;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (f2 != null && !f2.IsDisposed)
        {
            f2.Dispose();    
        }

        string a = textBox1.Text;
        f2 = new Form2(a);
        f2.Show();
    }

}

Upvotes: 1

Related Questions