Shukhrat Raimov
Shukhrat Raimov

Reputation: 2247

Multiple Windows Forms on one application

I have two windows forms, first is initial and second is invoked when button on the first is pressed. It's two different windows, with different tasks. I programmed for both MVP pattern. But in the Main() I have this:

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    ViewFirst viewFirst = new ViewFirst();//First Form
    PresenterFirst presenterFirst = new PresenterFirst(viewFirst);
    Application.Run(viewFirst);
}

And I Have Second Windows Form:

ViewSecond viewSecond = new ViewSecond();//Second Form
PresenterSecond presenterSecond = new PresenterSecond(viewSecond);

I want to run it in this app as soon as the button on the first is clicked. How could I do this? My button on the first WF is:

private void history_button_Click(object sender, EventArgs e)
{
    ViewSecond db = new ViewSecond();//second Form where I have sepparate WF.
    db.Show();
}

Upvotes: 0

Views: 12776

Answers (2)

Jason Ching
Jason Ching

Reputation: 2229

I am not sure where you are setting the presenter for your second form. You should set it when you are creating the ViewSecond form. Try this in the button click event:

private void history_button_Click(object sender, EventArgs e)
{
    ViewSecond viewSecond = new ViewSecond();//Second Form
    PresenterSecond presenterSecond = new PresenterSecond(viewSecond);
    db.Show();
}

Upvotes: 0

Picrofo Software
Picrofo Software

Reputation: 5571

Application.Run(Form mainForm) may only run ONE form per thread. If you try to run a second form on the same thread using Application.Run, the following exception might be thrown

System.InvalidOperationException was unhandled

Starting a second message loop on a single thread is not a valid operation. Use
Form.ShowDialog instead.

So, if you would like to call Application.Run to run another Form, you may call it under a new thread.

Example

private void history_button_Click(object sender, EventArgs e)
{
    Thread myThread = new Thread((ThreadStart)delegate { Application.Run(new ViewSecond()); }); //Initialize a new Thread of name myThread to call Application.Run() on a new instance of ViewSecond
    //myThread.TrySetApartmentState(ApartmentState.STA); //If you receive errors, comment this out; use this when doing interop with STA COM objects.
    myThread.Start(); //Start the thread; Run the form
}

Thanks,
I hope you find this helpful :)

Upvotes: 2

Related Questions