如何从函数设置表单控件属性 [英] How to set form control property from function

查看:55
本文介绍了如何从函数设置表单控件属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在主项目cpp文件中的函数中在Form1上设置我的label1的Text属性的值?

我可以在类内的事件处理程序中完成此操作,但这意味着将我的所有代码都写在头文件(Form1.h)中.肯定不是正确的做法吗???

在fnTest()中,智能提示会提示WindowsForms::Form1::label1,因此似乎可以识别.

我猜答案很简单(可能几乎令人尴尬-真是令人-目结舌!),但是我已经在网上搜索了(并以本网站为例),试图获得没有成功的答案.也许我使用了错误的搜索术语.我可以找到的所有示例都显示了驻留在头文件中的事件处理程序中的代码,这些代码已经可以使用,但是我不喜欢出于代码可移植性的想法.

发布代码,但这是标准的IDE生成的标准代码.我添加的只是fnTest()& Form1_Load()处理程序中的代码.

预先感谢,
戴夫.

Form1.h

How do I set the value of the Text property of my label1 on Form1, from within a function in the main project cpp file?

I can do it within the event handler inside the class, but that would mean writing all my code within the header file (Form1.h). Surely that''s not correct practice????

Within fnTest() the intellisense prompts to the WindowsForms::Form1::label1, so that seems to be recognised.

I''m guessing the answer is simple (probably almost embarrasingly so - a head-slapping moment!), but I''ve searched the net (& this site) trying to get an answer without success. Maybe I''m using the wrong search terminology. The examples I can find all show the code residing in the event handlers in the header file, which I can already get to work, but I don''t like the idea of that for code portability.

Posting the code but it is the stock standard IDE generated code. All I''ve added is fnTest() & the code inside the Form1_Load() handler.

Thanks in advance,
Dave.

Form1.h

#pragma once

void fnTest(int);

namespace WindowsForms {

    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();
            //
            //TODO: Add the constructor code here
            //
        }

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

    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->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D;
            this->label1->Location = System::Drawing::Point(34, 38);
            this->label1->Name = L"label1";
            this->label1->Size = System::Drawing::Size(100, 20);
            this->label1->TabIndex = 0;
            this->label1->Text = L"label1";
            this->label1->TextAlign = System::Drawing::ContentAlignment::MiddleCenter;
            //
            // Form1
            //
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(284, 264);
            this->Controls->Add(this->label1);
            this->Name = L"Form1";
            this->Text = L"Form1";
            this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
            this->ResumeLayout(false);

        }
#pragma endregion
    private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
                 label1->Text = "10";
                 fnTest();
             }
    };
}



C ++测试WinForms.cpp



C++ Test WinForms.cpp

// C++ Test WinForms.cpp : main project file.

#include "stdafx.h"
#include "Form1.h"

using namespace WindowsForms;

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
    // Enabling Windows XP visual effects before any controls are created
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);

    // Create the main window and run it
    Application::Run(gcnew Form1());
    return 0;
}

void fnTest() {
    WindowsForms::Form1::label1->Text = "11"; // <- this is the line that fails to build

}

推荐答案

您需要访问Form1类的实例对象-您可以执行以下操作:

1.在Form1类定义中添加以下内容-通常不认为将label1保留为公共字段是一个好主意.
You need to access an instance object of your Form1 class - you can do something like this:

1. Add the following to your Form1 class definition - leaving label1 as a public field is usually not considered a good idea.
public:
 void SetLabel1Text(String^ txt)
 {
   label1->Text = txt;
 }



2.通过对Form1类型的对象的实例引用访问新方法



2. Access your new method through an instance reference to an object of type Form1

Form1^ mainForm = gcnew Form1();
mainForm->SetLabel1Text( L"Some text" );
// This should also work as long as label1 is public:
//   mainForm->label1->Text = L"Some text";
Application::Run(mainForm);





private: System::Void Form1_Load(System::Object^   sender, System::EventArgs^ e) 
{
 label1->Text = "10"; // <-- works because Form1_Load a non-static member function of the Form1 class
 fnTest(); // <-- this method is not part of your class and needs access to an instance of your Form1 class
}



更新
这就像一种魅力(您的程序中应该只有一个消息循环-Application :: Run-):



Update
This works like a charm (You should only have one message loop - Application::Run - in your program):

// SampleWinforms.cpp : main project file.

#include "stdafx.h"
#include "Form1.h"

using namespace SampleWinforms;

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
    // Enabling Windows XP visual effects before any controls are created
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);

    // Create the main window and run it
    Form1^ mainForm = gcnew Form1();
    mainForm->label1->Text = L"Some Text";
    Application::Run(mainForm);
    return 0;
}



我添加了一个按钮"button1",并分配了以下事件处理程序



I''ve added a button "button1" and assigned the following event handler

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) 
{
 Form1^ newForm = gcnew Form1();
 newForm->label1->Text = L"Some Text On New Form";
 newForm->Show();
}


这使我可以创建一个新窗口并在显示标签之前对其进行修改.

更新2
要在当前表单上更改label1的Text属性:


This lets me create a new window and modify the label before showing it.

Update 2
To change the Text property of label1 on the current form:

private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) 
{ 
 label1->Text = L"Some Text On the Current Form"; 
}



假设只有一个Form1实例,下面将添加一个静态属性Instance,使您可以编写类似Form::Instance->label1->Text = L"Simple singleton";的内容.
由于Form :: Instance是静态的,因此只要存在,您就可以从任何包含"form1.h"的代码中访问该表单.



Assuming that there will only be a single instance of Form1, the following adds a static property Instance enabling you to write something like Form::Instance->label1->Text = L"Simple singleton";.
Since Form::Instance is static it will allow you to access the form, as long as it exists, from any code that includes the "form1.h"

public ref class Form1 : public System::Windows::Forms::Form
 {
private:
  typedef System::Windows::Forms::Form base;

  static Form1^ instance;
public:
  Form1(void)
  {
   InitializeComponent();
   instance = this;
  }

  property static Form1^ Instance
  {
   Form1^ get()
   {
    return instance;
   }
  }

protected:
  virtual void OnFormClosed(FormClosedEventArgs^ e) override
  {
   base::OnFormClosed(e);
   instance = nullptr; 
  }
// Rest of definition
}




问候
Espen Harlinn




Regards
Espen Harlinn


它砍了Form1.h的代码

...

#pragma地区Windows Form Designer生成的代码
///< summary>
///支持Designer的必需方法-请勿修改
///使用代码编辑器将此方法的内容.
///</summary>
void InitializeComponent(void)
{
this-> label1 =(gcnew System :: Windows :: Forms :: Label());
this-> SuspendLayout();
//
//label1
//
this-> label1-> BorderStyle = System :: Windows :: Forms :: BorderStyle :: Fixed3D;
this-> label1-> Location = System :: Drawing :: Point(34,38);
this-> label1->名称= L"label1";
this-> label1-> Size = System :: Drawing :: Size(100,20);
this-> label1-> TabIndex = 0;
this-> label1-> Text = L"label1";
this-> label1-> TextAlign = System :: Drawing :: ContentAlignment :: MiddleCenter;
//
//Form1
//
this-> AutoScaleDimensions = System :: Drawing :: SizeF(6,13);
this-> AutoScaleMode = System :: Windows :: Forms :: AutoScaleMode :: Font;
this-> ClientSize = System :: Drawing :: Size(284,264);
this->控件-> Add(this-> label1);
this->名称= L"Form1";
this->文本= L"Form1";
this->加载+ = gcnew System :: EventHandler(this,& Form1 :: Form1_Load);
this-> ResumeLayout(false);
}
#pragma endregion
私人:System :: Void Form1_Load(System :: Object ^发件人,System :: EventArgs ^ e){
label1->文本="10";
fnTest();
}
};
}
It chops the code for Form1.h

...

#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->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D;
this->label1->Location = System::Drawing::Point(34, 38);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(100, 20);
this->label1->TabIndex = 0;
this->label1->Text = L"label1";
this->label1->TextAlign = System::Drawing::ContentAlignment::MiddleCenter;
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(284, 264);
this->Controls->Add(this->label1);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
label1->Text = "10";
fnTest();
}
};
}


这篇关于如何从函数设置表单控件属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆