Y.S
Y.S

Reputation: 1862

winforms - show same form twice?

I have a quick and dirty winforms app I wrote, Which has a lot of controls logic & internal logic written within the Form() class.

I have a need to just open the same form twice (Where one form will be like a reference to other), and I'm looking for another quick and dirty solution.

That the code within my Program class:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Main());
        //Can I run Main() form a again as reference to the intial form?
    }
}

Yes, I'm aware best practice mentions I should separate to user controls, etc, please don't judge. Assistance is appreciated, thanks in advance.

Upvotes: 1

Views: 1418

Answers (4)

ArunPratap
ArunPratap

Reputation: 5020

you need to do that like this

static class Program
{

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        var thread = new Thread(ThreadStart);            
        thread.TrySetApartmentState(ApartmentState.STA);
        thread.Start(); 
        Application.Run(new Form1());

    }
    private static void ThreadStart()
    {
        Application.Run(new Form2()); 
    }

}

you can also Start the other forms from the Form.Load event of FirstForm.

private void Form1_Load(object sender, EventArgs e)
{
    Form2 form2 = new Form2();
    form2.Show();
}

Upvotes: 1

M.Nacher
M.Nacher

Reputation: 146

If you decide to go with Nii solution keep in mind recursive, because the solution as is will never end. You are going to need some control for only showing one form, something like this could work:

static int control = 0;
...
if (control == 0)
{
control = 1;
var newForm = new Main();
newForm.Show();
}

Upvotes: 1

Nii
Nii

Reputation: 568

you actually can, provided that the main objective is to just run another instance of the same form - in this case, the Main.

you can do this by hooking it up on the Main's instance prior to loading from the Application.Run(...); method of the Program.cs file, see below sample code snippet.

public void Main_Load()
{
    var newForm = new Main();
    newForm.Show();
}

its important not to use ShowDialog(); to not block the first Form.

Hope i got it right.

Upvotes: 1

styx
styx

Reputation: 1915

the best option for you is to add Click method on your form and there create a new instance of your form and show it

 private void Form1_Click(object sender, EventArgs e)
        {
            var frm = new Form1();
            frm.Show();
        }

now you can click everywhere on the form and it will open another instance of it

Upvotes: 1

Related Questions