我不确定您是如何添加 OvalShapes 或您使用的是什么类型的容器。为了将它们添加到 Windows 窗体控件,您需要使用 Slaks 提到的 shapeContainer。在此示例中,我创建了一个 shapeContainer 并将其添加到表单中,然后我使用 shapeContainers.Shapes.Add 方法将椭圆添加到ShapeCollection 类。我还将一个事件处理程序附加到椭圆的 Click 事件,以便我可以访问调用 Shape 以通过 EventHandler 的发送者对象更改其填充颜色。看看这是否适合你。
Imports Microsoft.VisualBasic.PowerPacks
Public Class Form1
Dim offset As Integer = 0
Dim OvalContainer As New ShapeContainer
Public Sub New()
' This call is required by the designer.
InitializeComponent()
OvalContainer.Size = New Size(Me.Width, 50)
Me.Controls.Add(OvalContainer)
OvalContainer.Location = New Point(0, 0)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oval As New OvalShape()
oval.Size = New Size(30, 40)
oval.Location = New Point(offset, 0)
oval.FillStyle = FillStyle.Solid
oval.FillColor = Color.Transparent
oval.BorderColor = Color.Black
oval.BorderWidth = 2
AddHandler oval.Click, AddressOf ShapeClick
OvalContainer.Shapes.Add(oval)
offset += 40
End Sub
Private Sub ShapeClick(sender As Object, e As EventArgs)
Dim oval As OvalShape = DirectCast(sender, OvalShape)
If oval.FillColor.Equals(Color.Red) Then
oval.FillColor = Color.Blue
Else
oval.FillColor = Color.Red
End If
End Sub
End Class
根据 OP 的说明进行编辑
当您创建椭圆添加时,oval.Name = "oval" & index
这将添加名称属性,该属性将使以下代码能够工作。
您可以像这样遍历 Shapes 集合(这是基于我上面的示例):
For Each o As OvalShape In OvalContainer.Shapes
If o.Name = "oval1" Then o.FillColor = Color.Azure
Next
ShapeContainer.Shapes.IndexOfKey
或者您可以使用方法搜索您正在寻找的确切椭圆形
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim index As Integer = OvalContainer.Shapes.IndexOfKey("oval1")
If index >= 0 Then
DirectCast(OvalContainer.Shapes(index), OvalShape).FillColor = Color.Purple
End If
End Sub