如何知道控件是TLabel?

How to know the Control is TLabel?

My Environment: C++ Builder XE4

how to copy all the TLabels parented with a TPanel on delphi to another TPanel?

我想在 C++ Builder 中实现以上代码。

我不知道如何在 C++ Builder 中实现下面的内容。

if ParentControl.Controls[i] is TLabel then

是否有任何函数可以获取 TLabel 或其他类型的类型?

我找到了 ClassName() 方法。

以下似乎有效。

static bool isTCheckBox(TControl *srcPtr)
{
    if (srcPtr->ClassName() == L"TCheckBox") {
        return true;
    }
    return false;
}

使用dynamic_cast:

if (dynamic_cast<TLabel*>(ParentControl->Controls[i]) != NULL)

这是该代码的翻译:

void __fastcall CopyLabels(TWinControl *ParentControl, TWinControl *DestControl)
{
   for(int i = 0; i < ParentControl->ControlCount; ++i)
   {
       if (dynamic_cast<TLabel*>(ParentControl->Controls[i]) != NULL)
       {
           TLabel *ALabel = new TLabel(DestControl);
           ALabel->Parent = DestControl;
           ALabel->Left   = ParentControl->Controls[i]->Left;
           ALabel->Top    = ParentControl->Controls[i]->Top;
           ALabel->Width  = ParentControl->Controls[i]->Width;
           ALabel->Height = ParentControl->Controls[i]->Height;
           ALabel->Caption= static_cast<TLabel*>(ParentControl->Controls[i])->Caption;
           //you can add manually more properties here like font or another 
        }
    }
}

话虽如此,这样效率会稍微高一些:

void __fastcall CopyLabels(TWinControl *ParentControl, TWinControl *DestControl)
{
   int count = ParentControl->ControlCount;
   for(int i = 0; i < count; ++i)
   {
       TLabel *SourceLabel = dynamic_cast<TLabel*>(ParentControl->Controls[i]);
       if (SourceLabel != NULL)
       {
           TLabel *ALabel = new TLabel(DestControl);
           ALabel->Parent = DestControl;
           ALabel->SetBounds(SourceLabel->Left, SourceLabel->Top, SourceLabel->Width, SourceLabel->Height);
           ALabel->Caption = SourceLabel->Caption;
           //you can add manually more properties here like font or another 
        }
    }
}

您可以使用 ClassType 方法作为:

if(Controls[i]->ClassType() == __classid(TLabel))
{
    ...
}