如何 return 来自 Windows 表单的值

How to return a value from Windows Form

我创建了一个名为 Project08 的 windows 表单应用程序。它有文件 Form1.hForm2.hProject08.cpp 和一些其他文件。我的使用场景简而言之是这样的:

如何才能将return用户名改为Project08.cpp?我的 Project08.cpp 在下面。我下面的代码是执行此操作的好方法吗?如果不能,你能推荐另一种方法吗?

// Project08.cpp : main project file.

#include "stdafx.h"
#include "Form1.h"
#include "Form2.h"
#include <stdio.h>

using namespace Project08;

[STAThreadAttribute] int main(array<System::String ^> ^args) {
// Enabling Windows XP visual effects before any controls are created
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false); 

// Create the main window and run it
Application::Run(gcnew Form1());
// assign user's name to a string here
Application::Run(gcnew Form2());
return 0; }

如果我的理解是正确的,您在 Form1 中有某种文本字段,用户可以在其中输入 his/her 姓名。您需要 return 该值返回到调用 Application::Run(Form^)

的函数

为此,我不会匿名创建 Form1 的实例。我会为它创建一个指针/引用,以便在构建后我可以访问它。

Form1^ form1 = gcnew Form1();
Application::Run(form1);

然后您需要在 Form1 中做一些事情 class。首先,当您单击该按钮时,您需要保存输入字段的文本,因为该表单将使 Dispose 上的所有组件无效。在按钮单击事件上添加单击处理程序以将输入组件的文本(在本例中为文本框)保存在 Class 成员变量中:

class Form1 [...]
{
    [...]
private:
    System::String^ m_Name; // Create a member variable for the value
    [...]
}

// Add a click Handler for your Button (do this in the Designer) and save the Text of the Text Box in it
System::Void Form1::button1_Click(System::Object^ sender, System::EventArgs^  e) 
{
    m_Name = textBoxName->Text;
}

然后我会为保存的值添加一个 getter 方法,您稍后可以通过主方法调用该方法:

System::String^ Form1::getUsername()
{
    return this->m_Name; // return the last saved Text of your Input control
}
只要表单显示,

Application::Run() 就会停止执行线程,因此在您的 Project08.cpp 文件中您将拥有:

[...]
Form1^ form1 = gcnew Form1(); // Create the instance and keep a pointer to it
Application::Run(form1); // Display the Form
System::String^ name = form1->getUsername(); // Get the saved Name after the Form disposed
// Do stuff with the name in Form 2
Application:Run(gcnew Form2(name));
[...]