简体   繁体   English

通过VC ++中的C ++代码访问GUI组件

[英]Accessing GUI components through C++ code in VC++

I have created a Windows Form Project in VC++ 2010 Express version. 我已经在VC ++ 2010 Express版本中创建了Windows窗体项目。 So, in that project I created a Form, which had only 1 button and 1 textbox. 因此,在该项目中,我创建了一个窗体,该窗体只有1个按钮和1个文本框。 The name of this form was Form1 . 该表单的名称为Form1

This button called a function FD written in a .cpp file in the same project. 此按钮称为在同一项目中的.cpp文件中编写的函数FD However, while running the code, I need to update the textbox with some text. 但是,在运行代码时,我需要用一些文本更新文本框。 I want to access the textbox through the .cpp file. 我想通过.cpp文件访问文本框。

I have tried the following: 我尝试了以下方法:
I included #include "Form1.h" and then wrote textBox1->Text="XYZ" . 我包括#include "Form1.h" ,然后编写了textBox1->Text="XYZ" However, while building it says that it cannot find any member called textBox1 . 但是,在构建时会说找不到任何名为textBox1成员。

How do I access the textbox from the .cpp file? 如何从.cpp文件访问文本框?

EDIT: 编辑:
FD.cpp

#include<stdafx.h>
#include "Form1.h" 
... //other includes  

void abc()
{
    //Some code
    textBox1->Text="String to be displayed."
    //Some code
}

Form1.h
This is simple GUI form, where a button called button1 and a textbox called textBox1 is added. 这是简单的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);
}

Or: 要么:

// FD.cpp
void abc(TextBox^ t)
{
    t->Text="String to be displayed."
    //Some code
}

// Form1.h
void button1_click()
{
    abc(textBox1);
}

Another way: make abc method return type String^ and set its return value in Form1 to textBox1 . 另一种方法:使abc方法返回类型String^ ,并将其返回值在Form1textBox1 Advantage: abc doesn't know anything about UI level. 优点: abc对UI级别一无所知。 Yet another way: events http://msdn.microsoft.com/en-us/library/58cwt3zh.aspx 另一种方式:事件http://msdn.microsoft.com/en-us/library/58cwt3zh.aspx

The reason you're getting this error is because you haven't specified whose textBox that is. 出现此错误的原因是,您尚未指定其文本框 It is not enough to #include the header file, you need to find a way to communicate with your Form1 object. #include头文件还不够,您需要找到一种与Form1对象进行通信的方法。 You can do this in several ways. 您可以通过多种方式执行此操作。

  1. Using a global pointer to the instance of your main Form1 that can be accessed from anywhere, 使用指向可以从任何地方访问的主Form1实例的全局指针,
  2. Using a local pointer to the instance of your main Form1 that is passed around and can be called upon, 使用本地指针来传递您的主Form1实例,并可以对其进行调用,
  3. Providing a friend function that can manipulate the data in the class (not recommended), 提供一个可以处理类中数据的好友功能(不推荐),

I would choose 2. 我会选择2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM