You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET运行时如何访问ShapeContainer内RectangleShape属性并控制显隐

解决方法

第一步:调整变量作用域与初始配置

你当前代码里ShapeContainer是局部变量,事件处理方法无法访问,同时你把整个容器的可见性设为了False,就算修改子矩形可见性也无法显示,首先做两处调整:

  1. 在窗体类内部、所有方法外声明窗体级的容器变量:
Private Cont As PowerPacks.ShapeContainer
  1. 原有初始化逻辑调整如下:
Cont = New ShapeContainer
Cont.Name = "rect"
Cont.Visible = True ' 容器本身需要可见,内部子形状才能正常显示
Me.Controls.Add(Cont)

For i As Integer = 2 To ImagePaths.Length
    ' 原有PictureBox创建逻辑保持不变
    
    Dim rect As New PowerPacks.RectangleShape
    rect.Location = New Point(pb.Left - 5, pb.Top - 5)
    rect.Size = New Size(pb.Width + 10, pb.Height + 25)
    rect.BorderWidth = 5
    rect.BorderStyle = Drawing2D.DashStyle.Dash
    rect.BorderColor = Color.Green
    rect.Name = "rect" & pb.Tag
    rect.Visible = False ' 单个矩形默认隐藏
    Cont.Shapes.Add(rect)

    ' 原有添加PictureBox到窗体的逻辑保持不变
Next

第二步:编写事件处理代码

MouseHover 事件(显示对应矩形)

Private Sub pb_MouseHover(sender As Object, e As EventArgs)
    Dim currentPb As PictureBox = CType(sender, PictureBox)
    Dim targetRectName = "rect" & currentPb.Tag.ToString()
    ' 按名称查找匹配的矩形
    Dim targetRect = Cont.Shapes.OfType(Of PowerPacks.RectangleShape)().FirstOrDefault(Function(r) r.Name = targetRectName)
    If targetRect IsNot Nothing Then
        targetRect.Visible = True
    End If
End Sub

MouseLeave 事件(隐藏对应矩形)

Private Sub pb_MouseLeave(sender As Object, e As EventArgs)
    Dim currentPb As PictureBox = CType(sender, PictureBox)
    Dim targetRectName = "rect" & currentPb.Tag.ToString()
    Dim targetRect = Cont.Shapes.OfType(Of PowerPacks.RectangleShape)().FirstOrDefault(Function(r) r.Name = targetRectName)
    If targetRect IsNot Nothing Then
        targetRect.Visible = False
    End If
End Sub

不使用LINQ的兼容写法

如果你的运行环境不支持LINQ语法,可以用遍历方式查找对应形状:

' 以MouseHover为例,MouseLeave仅修改赋值的Visible属性即可
Private Sub pb_MouseHover(sender As Object, e As EventArgs)
    Dim currentPb As PictureBox = CType(sender, PictureBox)
    Dim targetRectName = "rect" & currentPb.Tag.ToString()
    For Each shape In Cont.Shapes
        If TypeOf shape Is PowerPacks.RectangleShape AndAlso shape.Name = targetRectName Then
            CType(shape, PowerPacks.RectangleShape).Visible = True
            Exit For
        End If
    Next
End Sub

内容的提问来源于stack exchange,提问作者SluggerB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 07:54:03