Syb3rian
Syb3rian

Reputation: 171

One Windows Form needs an access to the components of another. What is the easiest implementation?

In my project I'm using C++/CLI and Windows Forms. I have two Forms. One is executed in main()

Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
Application::Run(gcnew FormA); 

Another FormB is executed from the instance of FormA

FormB^ fb = gcnew FormB();
fb->Show();

I need to change components of FormB from FormA. Normally they are in private: section of class FormB. Is there any nice way to do that different from simply making them all public? In Native C++ I would use friend class but it's not allowed in C++/CLI.

Upvotes: 0

Views: 38

Answers (2)

Hans Passant
Hans Passant

Reputation: 942020

C++/CLI has an access modifier that native C++ does not have. You are looking for internal:

Empowered by the strong support for modules in .NET. It is broader than friend but you have a pretty hard guarantee that whomever is messing with your private parts is never more than a few cubicles away from yours. Code that accesses internal members must be compiled into the same assembly. So your FormB class must be in the same project as your FormA class. The common case.

If you need the equivalent of friend across modules then you need the [InternalsVisibleTo] attribute. Exposing members with a public property would be another common way.

Upvotes: 2

Luc Morin
Luc Morin

Reputation: 5380

While providing public access to FormB's members may seem like a quick and easy solution, I would advise you to add some methods on FormB to perform said actions.

This way, you can call those methods from FormA, and at the same time retain proper encapsulation.

Hope this helps.

Upvotes: 1

Related Questions