c++builder - BCB : how to iterate over controls on a form?

标签 c++builder

我正在寻找一些 BCB 代码来迭代表单上的控件并获取有关它们的一些信息。

我尝试使用 myForm->ControlCounttypeid(myForm->Controls[i])但这给了我一些问题。

1) typeid(myForm->Controls[i])->Name总是给出 "TControl *"我希望得到“TEdit *”、“TMemo *”等

我可以使用

来解决这个问题吗
if (typeid(myForm->Controls[i]) == typeid(TEdit))

然后类型转换? (如果是这样,如何转换最好?)

2) 我如何(可能通过转换)获得控件的属性?例如,名称、宽度、高度等?

我真的很喜欢这里的实际代码(或一些实际代码的 URL);谢谢。


更新:因为我只需要针对我的特定情况测试 5 或 6 种不同类型的控件,我想我可以尝试 dynamic_cast<>每个人依次给他们每个人,但我似乎无法让它工作......

最佳答案

您假设强制转换是一个好主意并且使用 dynamic_cast 是这里的最佳选择,这在某种程度上是正确的。

如果您想遍历表单(或任何其他容器)的控件。不幸的是,我在这台计算机上没有我的 C++ Builder,所以我无法测试我给你的代码,虽然创建起来应该是一个微不足道的任务。

// You wanna start my iterating through the controls of the container
for (int i = 0; i < container->ControlCount; i++)
{
    // Let us extract the control at index i
    TControl *control = container->Controls[i];

    // Now we want to test whether this is any specific type, for instance a
    // TEdit or any TEdit descendant.
    TEdit *edit = dynamic_cast<TEdit *>(control);

    // If this control is a TEdit or any control deriving from it, we will have 
    // a pointer to it, if this is any other type, we will be left with a zero
    // pointer.
    if (edit)
    {
        // This is a TEdit control... we can now access TEdit only properties.
        edit->Text = "This is an edit control.";
    }

    // We do the same if we want to test for a TButton...
    TButton *button = dynamic_cast<TButton *>(control);

    // Again we test whether this was actually a button
    if (button)
    {
        // It is a button, again we can access TButton only properties...
        button->Caption = "This is a button"; 
        // Yeah ok not a TButton only one, but couldn't think of any.
    }

    // And so on...
}

您不需要为子控件的子控件递归函数,这些也包含在 VCL 中。在我看来,这是迄今为止测试特定类型的最简单的解决方案。我也尽量避免使用 RTTI 功能,但我就是这样。

如您所见,我的示例还展示了如何访问控件的属性和函数,甚至是特定于特定类型的属性和函数。但是,您提到的那些:NameWidthHeightTControl 都是通用的,因此没有必要转换以访问这些。

希望这对您有所帮助,从我的示例中应该清楚,变量 container 可以替换为您在自己的示例中使用的 myForm

关于c++builder - BCB : how to iterate over controls on a form?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2391325/

相关文章:

c++ - Borland C++ Builder 中的 Windows 子类化

c++ - 从 C++Builder 到 Visual Studio 2008

c++ - 从编译器运行和作为独立 exe 运行时,进程访问权限似乎有所不同

c++ - C++ 编译错误消息中的 __tpdsc__ 是什么意思?

C++Builder Clang std::less 找不到重载的运算符<

ssl - 获取 "EIdHTTPProtocolException with message ' HTTP/1.1 400 BAD REQUEST'”异常

c++ - 为什么鼠标按下会阻止组件的重新绘制?

android - C++ Builder - 获取 Activity 的结果

C++ FileRead 用法

c++ - 需要 std::vector 优化