我在 VC++ 2010 Express 版本中创建了一个 Windows 窗体项目。所以,在那个项目中,我创建了一个只有 1 个按钮和 1 个文本框的表单。此表单的名称是 Form1
。
这个按钮调用了一个函数FD
,写在同一个项目的.cpp
文件中。但是,在运行代码时,我需要用一些文本更新文本框。我想通过 .cpp
文件访问文本框。
我尝试了以下方法:
我包含了 #include "Form1.h"
,然后编写了 textBox1->Text="XYZ"
。但是,在构建时它说找不到任何名为 textBox1
的成员。
如何从 .cpp
文件访问文本框?
编辑:
FD.cpp
#include<stdafx.h>
#include "Form1.h"
... //other includes
void abc()
{
//Some code
textBox1->Text="String to be displayed."
//Some code
}
Form1.h
这是一个简单的 GUI 窗体,其中添加了一个名为 button1
的按钮和一个名为 textBox1
的文本框。
#include<FD.h>
//code generated by the GUI
void button1_click()
{
abc();
}
最佳答案
// FD.cpp
void abc(Form1^ f)
{
// Assuming that textBox1 is public. If not, make it public or make
// public get property
f->textBox1->Text="String to be displayed."
//Some code
}
// Form1.h
void button1_click()
{
abc(this);
}
或者:
// FD.cpp
void abc(TextBox^ t)
{
t->Text="String to be displayed."
//Some code
}
// Form1.h
void button1_click()
{
abc(textBox1);
}
另一种方法:使abc
方法返回类型为String^
,并将其在Form1
中的返回值设置为textBox1
.优点:abc
对 UI 级别一无所知。另一种方式:事件 http://msdn.microsoft.com/en-us/library/58cwt3zh.aspx
关于c++ - 在 VC++ 中通过 C++ 代码访问 GUI 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26908085/