我我不確定你怎麼樣正在添加您的OvalShapes或您正在使用的容器類型。爲了將它們添加到Windows窗體控件中,您需要使用Slaks提到的shapeContainer。在這個例子中,我創建一個shapeContainer並將其添加到窗體,然後我使用shapeContainers.Shapes.Add方法將橢圓添加到ShapeCollection Class。我還將一個事件處理程序附加到橢圓的Click事件中,以便我可以訪問調用的Shape以通過EventHandler的sender對象更改其填充顏色。看看這是否會爲你工作。每個操作的澄清
當您創建橢圓
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
編輯添加oval.Name = "oval" & index
這將增加name屬性,使 下面的代碼工作。
您可以通過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
我發現這對我需要做的第一部分非常有用,特別是因爲我已經有一個事件處理程序已經內置到橢圓中。現在我只需要能夠引用他們,當我點擊一個按鈕,所以我可以得到他們的狀態。我知道我可以在需要的時候明確地調出每個橢圓,但是當你有大量的對象時,這是非常不切實際的。我正在尋找的東西就像我編輯的原始問題。 – 110SidedHexagon
@ 110SidedHexagon查看我剛剛編輯的編輯是否可以幫助你 –
完美無缺! – 110SidedHexagon