我正在为一篇课程创建一个棋盘游戏。对于电路板,我使用一些嵌套的For循环运行通过2D数组在每个方块生成一个“Space”对象。
Space对象包含一个图片框和一些有关该空间的数据。
如何处理因点击生成的图片框而导致的事件,而无需为每个空间进行硬编码?
我注意到this问题似乎解决了这个问题,但它在C#中,我无法将其转换为VB.Net。
提前致谢!
编辑: 这就是电路板的生成方式
Dim board(23, 24) As Space
Private Sub GenerateBoard()
Dim spaceSize As New Size(30, 30)
Dim spaceLocation As New Point
Dim validity As Boolean
For Y = 0 To 24
For X = 0 To 23
spaceLocation.X = 6 + (31 * X)
spaceLocation.Y = 6 + (31 * Y)
If validSpaces(Y).Contains(X + 1) Then
validity = True
Else
validity = False
End If
board(X, Y) = New Space(validity, spaceSize, spaceLocation)
Me.Controls.Add(board(X, Y).imageBox)
board(X, Y).imageBox.BackColor = Color.Transparent
board(X, Y).imageBox.BringToFront()
Next
Next
End Sub
太空舱:
Public Class Space
Dim _active As Boolean
Dim _imageBox As PictureBox
Public Sub New(ByVal activeInput As Boolean, ByVal size As Size, ByVal location As Point)
_active = activeInput
_imageBox = New PictureBox
With _imageBox
.Size = size
.Location = location
.Visible = False
End With
End Sub
Property active As Boolean
Get
Return _active
End Get
Set(value As Boolean)
_active = value
End Set
End Property
Property imageBox As PictureBox
Get
Return _imageBox
End Get
Set(value As PictureBox)
_imageBox = value
End Set
End Property
Public Sub highlight()
With _imageBox
.Image = My.Resources.Highlighted_slab
.Visible = True
End With
End Sub
End Class
答案 0 :(得分:0)
首先由设计师创建的所有控件(文本框,标签......)也由代码生成,但VisualStudio会为您编写。如果您打开Designer文件(yourForm.Designer.vb
),那么您可以看到所有代码如何生成控件。
如果您想要pictureBox
的创建事件处理程序,那么:
//Initialize control
Private WithEvents _imageBox as PictureBox
然后创建一个事件处理程序方法:
Private Sub imageBox_Click(sender as Object, e as EventArgs)
//Your code
End Sub
然后在VB.NET中,您可以通过两种方式为Event分配一个事件处理程序
首先:在创建pictureBox(New PictureBox()
)之后的类构造函数中添加
AddHandler Me._imageBox, AddressOf Me.imageBox_Click
第二:在线我们创建了一个事件处理程序add next:
Private Sub imageBox_Click(sender as Object, e as EventArgs) Handles _imageBox.Click
//Your code
End Sub
请记住将您的pictureBox添加到表单控件YourForm.Controls.Add(spaceInstance.ImageBox)