0

我有两个窗体,第一个是初始窗体,第二个是在按下第一个按钮时调用的。这是两个不同的窗口,有不同的任务。我为这两种 MVP 模式编程。但在 Main() 我有这个:

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

我有第二个 Windows 窗体:

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

单击第一个按钮后,我想在此应用程序中运行它。我怎么能这样做?我在第一个 WF 上的按钮是:

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

2 回答 2

1

Application.Run(Form mainForm)每个线程只能运行一个表单。如果您尝试使用 在同一线程上运行第二个表单Application.Run,则可能会引发以下异常

System.InvalidOperationException was unhandled

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

所以,如果你想调用Application.Run运行另一个Form,你可以在一个新线程下调用它。

例子

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
}

谢谢,
我希望你觉得这有帮助:)

于 2012-12-16T04:30:46.130 回答
0

我不确定您在哪里为您的第二个表单设置演示者。您应该在创建 ViewSecond 表单时设置它。在按钮点击事件中试试这个:

private void history_button_Click(object sender, EventArgs e)
{
    ViewSecond viewSecond = new ViewSecond();//Second Form
    PresenterSecond presenterSecond = new PresenterSecond(viewSecond);
    db.Show();
}
于 2012-12-16T04:54:07.063 回答