c++ - 在 VC++ 中通过 C++ 代码访问 GUI 组件

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

我在 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/

相关文章:

c++ - 如何使用libevent检测文件锁何时释放?

c++ - 在 Arduino 中编程时避免使用指针和#defines?

windows - 可以更改 Android 虚拟设备的保存位置吗?

c# - .Net Windows Forms ListView OwnerDraw LargeImageList 泄漏

c# - "Hot Track"对 Windows 窗体用户控件的影响

c# - 表单获得焦点时 ObjectListView 上的黑色背景和伪像

c++ - 使用 SFINAE 让 `std::get` 玩得更好

c++ - make_shared 与模板构造函数

windows - GetScheduledTaskInfo NextRunTime 错误

windows - 处理 Windows 批处理脚本中的引号