我有两个窗口形式,第一个是初始,第二个是在按下第一个按钮时调用的。它是两个不同的窗口,具有不同的任务。我为两个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();
}
答案 0 :(得分: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
}
谢谢, 我希望你觉得这很有帮助:)
答案 1 :(得分:0)
我不确定您为第二张表单设置演示者的位置。您应该在创建ViewSecond表单时进行设置。在按钮单击事件中尝试此操作:
private void history_button_Click(object sender, EventArgs e)
{
ViewSecond viewSecond = new ViewSecond();//Second Form
PresenterSecond presenterSecond = new PresenterSecond(viewSecond);
db.Show();
}