In Visual Studio C++/CLI, how can I access the elements of another form from one form?

Let there be two forms: Form1. h and Form2.h

How to use the form Form2.h to access the elements Form1.h

Reading various forums, I realized the following: it is necessary to declare a pointer to the first form in the constructor parameters of the second form:

  Form2(Form1^ copyForm1)
  {
      // код конструктора   
  } ;

And in the first form, submit this as a constructor parameter

  Form ^ Form2rel = gcnew Form2(this);

Then the elements of the first form can be accessed simply through the pointer, for example

  copyForm1->Label1->Text

The essence of the approach is clear, but only the pointer of the form Form1^ copyForm1 is not declared, since the second form does not see the class Form1, the studio writes "invalid Form1 ID", and why is not clear...

They have one namespace Project1, if you assign Project1:: Form1^ copyForm1, then writes "Form1 is not a member of Project1"

Doing #include "Form1.h" in Form2.h doesn't help - errors pop up.

Please explain what the problem is.

Author: Nicolas Chabanovsky, 2012-02-06

1 answers

In my opinion, you have the wrong approach to the problem, which is that you need to change the contents of the elements of the form Form1 in the form Form2. There are several ways to solve this problem:

  1. Declare a delegate and use a message through this delegate to notify Form1 that it has changed its fields.
  2. Declare an interface of the form

    interface IEvent
    {
      virtual void SendText(String^ text) = 0;
     };
    

Inherit Form1 from IEvent, implement the SendText method, and pass a pointer to the constructor IEvent:

#include "ivent.h" // файл в котором объявлен IEvent
Form2(IEvent^ pEvent);

When you need to change the contents of the field in Form2, then just write pEvent->SendText("qwerty");.

The second method is very similar to what you wanted, only there is no hard dependency on Form1 in Form2.

 3
Author: IAZ, 2012-02-07 17:32:27