首页 > 解决方案 > 滚动父控件时如何获取可见的子控件?

问题描述

在此处输入图像描述

将标签添加到面板时的代码:

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For i As Integer = 0 To 50
        Panel1.Controls.Add(New Label With {.BorderStyle = BorderStyle.FixedSingle, .AutoSize = False, .Visible = True, .Text = i.ToString, .Width = 50, .Dock = DockStyle.Left})
    Next
End Sub

现在,如何在面板滚动时获取可见标签,也许在Panel1.Scroll事件中?

 Private Sub Panel1_Scroll(sender As Object, e As ScrollEventArgs) Handles Panel1.Scroll
    If e.ScrollOrientation = ScrollOrientation.HorizontalScroll Then
        'HOW ?????
    End If
End Sub

标签: vb.netwinforms

解决方案


滚动时可以获得可见的标签。您必须查看 of 中的哪个ClientRectangle标签Panel1。这是 的可视区域Panel1
在您的问题中,不清楚您想对可见标签做什么。假设您想在Textbox1滚动时写入可查看标签的名称Panel1。您可以使用以下代码执行此操作:

Private Sub Panel1_Scroll(sender As Object, e As ScrollEventArgs) Handles Panel1.Scroll
    Dim myBounds as Rectangle = Panel1.ClientRectangle
    TextBox4.Text = ""
    For Each control in Panel1.Controls
        Dim label as Label = CType(control,Label)
        if label.Location.X > myBounds.X And label.Location.X<myBounds.Width Or label.Location.X+label.Width>myBounds.X AND label.Location.X+label.Width<myBounds.Width Then
            TextBox4.Text +=  CType( control,Label).Text + vbCrLf
        End If
    Next
End Sub

请注意,上述方法列出了所有部分可见的标签。如果您只想列出所有完全可见的标签,只需更改代码:

Private Sub Panel1_Scroll(sender As Object, e As ScrollEventArgs) Handles Panel1.Scroll
    Dim myBounds as Rectangle = Panel1.ClientRectangle
    TextBox4.Text = ""
    For Each control in Panel1.Controls
        Dim label as Label = CType(control,Label)
        if label.Location.X > myBounds.X And label.Location.X<myBounds.Width AND label.Location.X+label.Width>myBounds.X AND label.Location.X+label.Width<myBounds.Width Then
            TextBox4.Text +=  CType( control,Label).Text + vbCrLf
        End If
    Next
End Sub

推荐阅读