如何为动态创建的按钮编写函数Click()? [英] how to write a function Click() for dynamic created button?

查看:114
本文介绍了如何为动态创建的按钮编写函数Click()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图编写一个简单的VCL程序用于教育目的(动态创建的表单,控件等)。拥有这样的示例代码:

Trying to write a simple VCL program for educating purposes (dynamicly created forms, controls etc). Have such a sample code:

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    TForm* formQuiz = new TForm(this);
    formQuiz->BorderIcons = TBorderIcons() << biSystemMenu >> biMinimize >> biMaximize;
    formQuiz->Position = TPosition::poDesktopCenter;
    formQuiz->Width = 250;
    formQuiz->Height = 250;
    formQuiz->Visible = true;

    TButton* btnDecToBin = new TButton(formQuiz);
    btnDecToBin->Parent = formQuiz;
    btnDecToBin->Left = 88;
    btnDecToBin->Top = 28;
    btnDecToBin->Caption = "Dec to Bin";
    btnDecToBin->Visible = true;
}

我想知道如何为动态创建的按钮编写函数,所以它会单击按钮时被调用。在此示例中,我需要一个'btnDecToBin-> Click();'函数,但我不知道该将其放置在何处。

I wonder how can i write a function for dynamic created button, so it would be called when the button is clicked. In this example i need a 'btnDecToBin->Click();' func but i don't know where should i place it.

内部' void __fastcall TForm1 :: Button1Click(TObject * Sender){} '?

我将不胜感激任何输入,一些关键字也适用于Google。

I will appreciate any input, some keywords for google too.

推荐答案

您可以做两件事,可以创建一个动作并将其与按钮关联,或者您可以像这样创建函数:

You could do two things, you could either create an action and associate it with the button, or you could make a function like so:

void __fastcall TForm1::DynButtonClick(TObject *Sender)
{
    // Find out which button was pressed:
    TButton *btn = dynamic_cast<TButton *>(Sender);

    if (btn)
    {
        // Do action here with button (btn).
    }
}

您可以通过设置OnClick将其绑定到按钮实例属性 btnDecToBin-> OnClick = DynButtonClick 请注意,该函数位于Form1表单内。由于闭包的性质(编译器特定的添加项),这将起作用。如果您在 formQuiz 之前删除 Form1 而没有删除对click事件的引用,就会出现问题。在许多情况下,在这种情况下使用Action可能是更干净的解决方案。

You bind it to the button instance by setting the OnClick property btnDecToBin->OnClick = DynButtonClick please note that the function is inside the form Form1. This will work due to the nature of closures (compiler specific addition). The problem comes if you delete Form1 before formQuiz without removing the reference to the click event. In many ways it might be a more clean solution to use an Action in this case.

编辑:您的测验表单具有标准布局,则可以从 TForm 继承自定义 TQuizForm 类。这样,您不必在每次创建表单时都绑定事件。

On other way to do this, if you have a standard layout for your quizforms, you could make a custom TQuizForm class inheriting from TForm. In this way you wouldn't have to bind the event each time you create the form.

这篇关于如何为动态创建的按钮编写函数Click()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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