#pragma once
namespace EjemploVariables {
using namespace System;
using namespace System::Windows::Forms;
public ref class Form1 : public System::Windows::Forms::Form {
public:
Form1(void) {
InitializeComponent();
}
protected:
~Form1() {
if (components) {
delete components;
}
}
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Label^ label2;
// ... otros controles
private: System::ComponentModel::Container ^components;
void InitializeComponent(void) {
this->label1 = (gcnew System::Windows::Forms::Label());
this->label2 = (gcnew System::Windows::Forms::Label());
// ... inicialización de otros controles
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(10, 10);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(46, 17);
this->label1->TabIndex = 0;
this->label1->Text = L"label1";
//
// label2
//
this->label2->AutoSize = true;
this->label2->Location = System::Drawing::Point(10, 40);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(46, 17);
this->label2->TabIndex = 1;
this->label2->Text = L"label2";
// ... inicialización de otros controles
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
// Utilizando reflexión para acceder a propiedades de controles por su nombre
SetLabelText("label1", "Prueba 1");
SetLabelText("label2", "Prueba 2");
// ... establecer propiedades de otros controles
}
void SetLabelText(String^ controlName, String^ text) {
// Obtener el tipo del formulario
Type^ formType = this->GetType();
// Obtener el campo del control por el nombre
System::Reflection::FieldInfo^ field = formType->GetField(controlName, System::Reflection::BindingFlags::NonPublic | System::Reflection::BindingFlags::Instance);
// Verificar si el campo fue encontrado
if (field != nullptr) {
// Obtener el valor del campo (es un control Label en este ejemplo)
Label^ labelControl = dynamic_cast<Label^>(field->GetValue(this));
// Verificar si el control es del tipo Label
if (labelControl != nullptr) {
// Establecer el texto del control
labelControl->Text = text;
}
}
}
};
}