【问题标题】:Generic form to create components创建组件的通用表单
【发布时间】:2011-11-08 19:57:13
【问题描述】:

我正在尝试在 GUI 中创建一个大方且快速的创建组件,我所做的代码如下,但我知道他没有做我想要的,我也不知道我该怎么做。

#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;

public ref class GUI : public Form
{
private:
    int x, y;
    String^ text;
    Button^ btm;

public:
    GUI(int _x, int _y, String^ caption)
    {
        x = _x;
        y = _y;
        text = caption;
        init_btm();
    }
    void init_btm()
    {
        btm = gcnew Button();
        btm->Location = Point(x, y);
        btm->Text = text;
        Controls->Add(btm);
    }
};

int main(array<System::String ^> ^args)
{
    Application::Run(gcnew GUI(20,20,"Ola mundo"));
    return 0;
}

我正在尝试创建这样的东西......

而是一种动态的方式来创建组件并将组件添加到表单中 好吧,我要做的是创建一个可以访问它的类,并创建多个按钮,而这个类,在 Form 上添加这些按钮可能是这样的:

ADD_BTM^ btm;
btm->Add(20,20,"Hello 1");
btm->Add(20,20,"Hello 2");

您可能还想知道,为什么我没有“设计”我的界面,我正在学习 C++/CLI,而我正在尝试创建这个程序,只是为了学习。 感谢您的帮助。

【问题讨论】:

  • 您能否再描述一下这个问题?如果有的话,它显示了什么?有错误吗?
  • 好的,我编辑了帖子...
  • 我很好奇,你为什么要尝试使用 C++/CLI?

标签: winforms visual-c++ c++-cli


【解决方案1】:

你已经知道如何在表单中添加新按钮了,你只需要给方法添加参数然后重复调用:

GUIpublic 部分:

void AddButton(int x, int y, String^ caption)
{
    auto button = gcnew Button();
    button->Location = Point(x, y);
    button->Text = caption;
    Controls->Add(button);
}

main:

auto form = gcnew GUI();

form->AddButton(20, 20, "Hello 1");
form->AddButton(40, 40, "Hello 2");

Application::Run(form);

(代码使用 C++11 中的auto。如果你不使用 VS 2010,只需将它们替换为实际类型即可。)

【讨论】:

  • 在按钮中添加一个功能句柄,例如,如果我点击按钮,显示de messagebox...。我该怎么做?
猜你喜欢
  • 2022-11-21
  • 1970-01-01
  • 2014-11-20
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
  • 2016-10-15
  • 2014-05-20
  • 2017-01-18
相关资源
最近更新 更多