从窗体外部的公共方法更新Windows窗体中的TextBox

时间:2012-05-23 22:18:45

标签: winforms textbox c++-cli

我有一个带有Form1.hButton的窗体(TextBox)。初始化表单时TextBox为空。单击按钮时,将调用表单外部的方法,并应更新TextBox。如何从非表单类更新TextBox?以下是我的示例代码:

// Form1.h
private: System::Void findResultButton_Click(System::Object^  sender, System::EventArgs^  e) {
    FirstResults* firstResults = new FirstResults();
    firstResults->findResult();
}

// FirstResults.cpp
void FirstResults::findResult() { 
    // do some calculations here and find result.
    // write the result value to a .txt file.
    // Update TextBox in Form1.h with result value.
}

1 个答案:

答案 0 :(得分:2)

首先,您需要创建表单的静态实例。 然后在任何.cpp文件中,您只想访问TextBox1或TextArea

public ref class Form1 : public System::Windows::Forms::Form
{
public:
    static Form1^ myForm1;

    Form1(void)
    {
        InitializeComponent();
        myForm1 = this;
        //
        //TODO: Add the constructor code here
        //
    }
}

然后在.cpp #include "form1.h"

Form1^ myform1 = gcnew Form1();
Form1::myForm1->textBox1->Text = L" FROM the main.cpp ";

或者如果你需要

System::Windows::Forms::myform1->textBox1->Text = L" FROM the main.cpp ";