关闭表单并打开另一个表单而不关闭应用程序

时间:2012-11-07 15:04:14

标签: winforms visual-c++ c++-cli

我希望我的代码关闭当前表单并打开另一个表单而不关闭应用程序(在Visual C ++ 2010 Express中)。这是我正在尝试使用的代码:

Form2^ form2=gcnew Form2();
form2->Show();
this->Close();

应在所有表单关闭后关闭应用程序,因此this->Hide()将无效。

1 个答案:

答案 0 :(得分:2)

打开项目中的主.cpp源代码文件,该文件包含main()函数。您将在该函数中看到与此类似的语句:

Application::Run(gcnew Form1);

Run()方法的这个重载将导致程序在主要形式的app关闭时终止。如果你想让它保持运行,那么你需要以不同的方式做到这一点。就像使用普通的Run()重载一样,并在关闭所有窗口时调用Application :: Exit()。您可以通过订阅FormClosed事件来完成此操作,如下所示:

void ExitWhenLastWindowClosed(Object^ sender, FormClosedEventArgs^ e) {
    if (Application::OpenForms->Count == 0) Application::Exit();
    else Application::OpenForms[0]->FormClosed += gcnew FormClosedEventHandler(ExitWhenLastWindowClosed);
}

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false); 
    Form1^ first = gcnew Form1();
    first->FormClosed += gcnew FormClosedEventHandler(ExitWhenLastWindowClosed);
    first->Show();
    Application::Run();
    return 0;
}