0

Есть форма Form1 с элементом label и подключенный файл AnotherClass.h.

Как из класса AnotherClass получить доступ к элементу label1, который находится, по сути, в другом классе.

Из метода SetTextToLabel, который находится в классе AnotherClass:

#pragma once
#include "AnotherClass.h"

namespace TestProject {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;

    /// <summary>
    /// Summary for Form1
    ///
    /// WARNING: If you change the name of this class, you will need to change the
    ///          'Resource File Name' property for the managed resource compiler tool
    ///          associated with all .resx files this class depends on.  Otherwise,
    ///          the designers will not be able to interact properly with localized
    ///          resources associated with this form.
    /// </summary>
    public ref class Form1 : public System::Windows::Forms::Form
    {
    public:
        Form1(void)
        {
            InitializeComponent();
            this->anotherClass = gcnew AnotherClass();
            this->anotherClass->SetTextToLabel("AAA");
        }

    protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~Form1()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::Label^  label1;
    private: AnotherClass^ anotherClass;

    private:
        /// <summary>
        /// Required designer variable.
        /// </summary>
        System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        void InitializeComponent(void)
        {
            this->label1 = (gcnew System::Windows::Forms::Label());
            this->SuspendLayout();
            // 
            // label1
            // 
            this->label1->AutoSize = true;
            this->label1->Location = System::Drawing::Point(13, 13);
            this->label1->Name = L"label1";
            this->label1->Size = System::Drawing::Size(35, 13);
            this->label1->TabIndex = 0;
            this->label1->Text = L"label1";
            // 
            // Form1
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(284, 262);
            this->Controls->Add(this->label1);
            this->Name = L"Form1";
            this->Text = L"Form1";
            this->ResumeLayout(false);
            this->PerformLayout();

        }
#pragma endregion
    };
}

И вот класс, в котором происходят все действия:

#include "StdAfx.h"

namespace TestProject {

    using namespace System;

    public ref class AnotherClass {
    public:
        AnotherClass(void) {

        }
    protected:
        ~AnotherClass(void) {

        }
    public:
        void SetTextToLabel(System::String^ text) {

            // Здесь происходят какие то действия, после чего нужно для label1 заменить текст.
            // Это тестовый проект для примера проблемы.
            // На реальном проекте этот метод запускается не из файла Form1.h,
            // а запускается сам по событию
            // Пробовал TestProject::Form1^ form1 = gcnew Form1();
            // появляется ошибка 'Form1' : is not a member of 'TestProject'
        }
    };
}
8
  • Любопытно, так как неожиданно для меня, почему вы занимаетесь C++/CLI? Это по работе или по учебе? 8 июл 2015 в 17:44
  • @VladfromMoscow: По учёбе, думаю. Задали написать программу с графикой, но на C++.
    – VladD
    8 июл 2015 в 17:45
  • Кто-нибудь, найдите дубликат. Вопросов о том, как двум классам помириться между собой, в контексте именно C++/CLI + Winforms, было примерно миллион.
    – VladD
    8 июл 2015 в 17:46
  • Нужно для себя, изучаю подключение всякой электроники к компьютеру. На C++ удается запрограммировать USB реле, купюроприемник, и т.д. Пробовал смотреть подобные вопросы, но все же не удалось получить доступ к элементам формы из другого класса. 8 июл 2015 в 18:16
  • Мне нужно узнать хотя бы способ обращения к нестатическим методам Form1 из другого класса. Предположим в классе Form1 есть метод SetLabelText, который задает текст для label. Так как этот метод сам находится в классе Form1, то уже не будет проблемы получить из него доступ к label. Но вопрос, как обратиться к этому методу из другого класса? 8 июл 2015 в 18:28

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.