【问题标题】:Closing a form and opening another without closing the application在不关闭应用程序的情况下关闭表单并打开另一个表单
【发布时间】:2013-12-26 12:54:24
【问题描述】:

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

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

当所有表单都关闭后,应用程序应该关闭,所以this->Hide() 将不起作用。

【问题讨论】:

  • 我完全了解 Windows 编程,但您应该说出您当前代码的结果。有什么不好的地方?
  • @BoBTFish 应用程序在打开新表单并运行第三行时关闭。

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


【解决方案1】:

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

Application::Run(gcnew Form1);

Run() 方法的这种重载将导致程序在应用程序的主窗体关闭时终止。如果您想保持它运行,那么您需要以不同的方式执行此操作。就像使用普通的 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;
}

【讨论】:

    猜你喜欢
    • 2013-03-13
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 2017-07-06
    • 2014-02-02
    • 2013-06-22
    • 2015-06-14
    • 1970-01-01
    相关资源
    最近更新 更多