Rohit Shinde
Rohit Shinde

Reputation: 1603

Accessing GUI components through C++ code in VC++

I have created a Windows Form Project in VC++ 2010 Express version. So, in that project I created a Form, which had only 1 button and 1 textbox. The name of this form was Form1.

This button called a function FD written in a .cpp file in the same project. However, while running the code, I need to update the textbox with some text. I want to access the textbox through the .cpp file.

I have tried the following:
I included #include "Form1.h" and then wrote textBox1->Text="XYZ". However, while building it says that it cannot find any member called textBox1.

How do I access the textbox from the .cpp file?

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.

#include<FD.h>
//code generated by the GUI
void button1_click()
{
    abc();
}

Upvotes: 1

Views: 1472

Answers (2)

Alex F
Alex F

Reputation: 43331

// 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. Advantage: abc doesn't know anything about UI level. Yet another way: events http://msdn.microsoft.com/en-us/library/58cwt3zh.aspx

Upvotes: 2

user2233125
user2233125

Reputation:

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. 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,
  2. Using a local pointer to the instance of your main Form1 that is passed around and can be called upon,
  3. Providing a friend function that can manipulate the data in the class (not recommended),

I would choose 2.

Upvotes: 0

Related Questions